Conditional build based on environment using Webpack

前端 未结 9 653
爱一瞬间的悲伤
爱一瞬间的悲伤 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:24

    While this is not the best solution, it may work for some of your needs. If you want to run different code in node and browser using this worked for me:

    if (typeof window !== 'undefined') 
        return
    }
    //run node only code now
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-30 22:27

    Use envirnment variables to create dev and prod deployments:

    https://webpack.js.org/guides/environment-variables/

    0 讨论(0)
提交回复
热议问题