Mocking external imports in development environmen

2019-08-26 08:02发布

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

2条回答
The star\"
2楼-- · 2019-08-26 08:27

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.

查看更多
Viruses.
3楼-- · 2019-08-26 08:45

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') : new MockedOverwolf();

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

查看更多
登录 后发表回答