Skip to content Skip to sidebar Skip to footer

Mocking External Imports In Development Environment Using Webpack And React

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 w

Solution 1:

One possible solution is to keep using the overwolf defined as an external (read more here), and use a polyfill for other browsers:

In your index.html include an overwolf.js script which will provide the mock object to use.

Example using HtmlWebpackPlugin and html-webpack-template to generate the index.html as part of the build process. Include in your plugins array:

new HtmlWebpackPlugin({
    template: './node_modules/html-webpack-template/index.ejs',
    inject: false,
    scripts: ['/overwolf.js']
})

And this is an example for the included overwolf.js previously:

if (!window.overwolf) {
    window.overwolf = {
        foo() {
            console.info('overwolf now has foo function!');
        }
    };
}

Hope this helps!

Check also this webpack-demo project. I think it would help you with some configurations.

Solution 2:

I also found a rather simple solution on my own.

Instead of importing the external this also works:

const overwolf = process.env.NODE_ENV === 'production' ? require('overwolf') : newMockedOverwolf();

Webpack will not complain about this in the dev environment and in production require will still give me the real API.

Post a Comment for "Mocking External Imports In Development Environment Using Webpack And React"