Conditional build based on environment using Webpack

前端 未结 9 673
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 21:40

I have some things for development - e.g mocks which I would like to not bloat my distributed build file with.

In RequireJS you can pass a config in a plugin file an

9条回答
  •  半阙折子戏
    2020-11-30 22:26

    You can use the define plugin.

    I use it by doing something as simple as this in your webpack build file where env is the path to a file that exports an object of settings:

    // Webpack build config
    plugins: [
        new webpack.DefinePlugin({
            ENV: require(path.join(__dirname, './path-to-env-files/', env))
        })
    ]
    
    // Settings file located at `path-to-env-files/dev.js`
    module.exports = { debug: true };
    

    and then this in your code

    if (ENV.debug) {
        console.log('Yo!');
    }
    

    It will strip this code out of your build file if the condition is false. You can see a working Webpack build example here.

提交回复
热议问题