In my React Application I am using an API which is provided at runtime as a global variable by the Browser in which the application runs.
To make the Webpack compilation process work I have added this into the webpack config:
externals: {
overwolf : 'overwolf'
}
It is then imported like this
import overwolf from 'overwolf'
This works fine when I built my production application and run it inside the Browser.
However for the webpack development server, as well as my tests I want to be able to run them from a standard browser where the external will not be available. I am not quite sure how to make this work as the dev server will always complain about the import and my attempts to make conditional imports did not work out so far.
What I would like to achieve is to mock the overwolf variable, so that webpack dev server will compile and let me run my code with the mocked version.
My attempt was like this
import overwolf from 'overwolf'
export function overwolfWrapper() {
if(process.env.NODE_ENV !== 'production') {
return false;
}
else {
return overwolf;
}
}
Which results in the following error on the webpack development server
ReferenceError: overwolf is not defined
overwolf
C:/Users/jakob/Documents/private/projects/koreanbuilds-overwolf2/external "overwolf":1
One possible solution is to keep using the
overwolf
defined as anexternal
(read more here), and use a polyfill for other browsers:In your
index.html
include anoverwolf.js
script which will provide the mock object to use.Example using
HtmlWebpackPlugin
andhtml-webpack-template
to generate theindex.html
as part of the build process. Include in yourplugins
array:And this is an example for the included
overwolf.js
previously:Hope this helps!
Check also this webpack-demo project. I think it would help you with some configurations.
I also found a rather simple solution on my own.
Instead of importing the external this also works:
Webpack will not complain about this in the dev environment and in production require will still give me the real API.