Passing environment-dependent variables in webpack

后端 未结 15 2232
醉酒成梦
醉酒成梦 2020-11-22 12:46

I\'m trying to convert an angular app from gulp to webpack. in gulp I use gulp-preprocess to replace some variables in the html page (e.g. database name) depending on the NO

15条回答
  •  生来不讨喜
    2020-11-22 13:09

    I found the following solution to be easiest to setup environment variable for Webpack 2:

    For example we have a webpack settings:

    var webpack = require('webpack')
    
    let webpackConfig = (env) => { // Passing envirmonment through
                                    // function is important here
        return {
            entry: {
            // entries
            },
    
            output: {
            // outputs
            },
    
            plugins: [
            // plugins
            ],
    
            module: {
            // modules
            },
    
            resolve: {
            // resolves
            }
    
        }
    };
    
    module.exports = webpackConfig;
    

    Add Environment Variable in Webpack:

    plugins: [
        new webpack.EnvironmentPlugin({
           NODE_ENV: 'development',
           }),
    ]
    

    Define Plugin Variable and add it to plugins:

        new webpack.DefinePlugin({
            'NODE_ENV': JSON.stringify(env.NODE_ENV || 'development')
        }),
    

    Now when running webpack command, pass env.NODE_ENV as argument:

    webpack --env.NODE_ENV=development
    
    // OR
    
    webpack --env.NODE_ENV development
    

    Now you can access NODE_ENV variable anywhere in your code.

提交回复
热议问题