Passing environment-dependent variables in webpack

后端 未结 15 1921
醉酒成梦
醉酒成梦 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:03

    Since my Edit on the above post by thevangelist wasn't approved, posting additional information.

    If you want to pick value from package.json like a defined version number and access it through DefinePlugin inside Javascript.

    {"version": "0.0.1"}
    

    Then, Import package.json inside respective webpack.config, access the attribute using the import variable, then use the attribute in the DefinePlugin.

    const PACKAGE = require('../package.json');
    const _version = PACKAGE.version;//Picks the version number from package.json
    

    For example certain configuration on webpack.config is using METADATA for DefinePlugin:

    const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
      host: HOST,
      port: PORT,
      ENV: ENV,
      HMR: HMR,
      RELEASE_VERSION:_version//Version attribute retrieved from package.json
    });
    
    new DefinePlugin({
            'ENV': JSON.stringify(METADATA.ENV),
            'HMR': METADATA.HMR,
            'process.env': {
              'ENV': JSON.stringify(METADATA.ENV),
              'NODE_ENV': JSON.stringify(METADATA.ENV),
              'HMR': METADATA.HMR,
              'VERSION': JSON.stringify(METADATA.RELEASE_VERSION)//Setting it for the Scripts usage.
            }
          }),
    

    Access this inside any typescript file:

    this.versionNumber = process.env.VERSION;
    

    The smartest way would be like this:

    // webpack.config.js
    plugins: [
        new webpack.DefinePlugin({
          VERSION: JSON.stringify(require("./package.json").version)
        })
      ]
    

    Thanks to Ross Allen

    0 讨论(0)
  • 2020-11-22 13:04

    Just another option, if you want to use only a cli interface, just use the define option of webpack. I add the following script in my package.json :

    "build-production": "webpack -p --define process.env.NODE_ENV='\"production\"' --progress --colors"
    

    So I just have to run npm run build-production.

    0 讨论(0)
  • 2020-11-22 13:04

    Here is a way that has worked for me and has allowed me keep my environment variables DRY by reusing a json file.

    const webpack = require('webpack');
    let config = require('./settings.json');
    if (__PROD__) {
        config = require('./settings-prod.json');
    }
    
    const envVars = {};
    Object.keys(config).forEach((key) => {
        envVars[key] = JSON.stringify(config[key]);
    });
    
    new webpack.DefinePlugin({
        'process.env': envVars
    }),
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 13:15

    There are two basic ways to achieve this.

    DefinePlugin

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

    Note that this will just replace the matches "as is". That's why the string is in the format it is. You could have a more complex structure, such as an object there but you get the idea.

    EnvironmentPlugin

    new webpack.EnvironmentPlugin(['NODE_ENV'])
    

    EnvironmentPlugin uses DefinePlugin internally and maps the environment values to code through it. Terser syntax.

    Alias

    Alternatively you could consume configuration through an aliased module. From consumer side it would look like this:

    var config = require('config');
    

    Configuration itself could look like this:

    resolve: {
        alias: {
            config: path.join(__dirname, 'config', process.env.NODE_ENV)
        }
    }
    

    Let's say process.env.NODE_ENV is development. It would map into ./config/development.js then. The module it maps to can export configuration like this:

    module.exports = {
        testing: 'something',
        ...
    };
    
    0 讨论(0)
  • 2020-11-22 13:17

    You can pass any command-line argument without additional plugins using --env since webpack 2:

    webpack --config webpack.config.js --env.foo=bar
    

    Using the variable in webpack.config.js:

    module.exports = function(env) {
        if (env.foo === 'bar') {
            // do something
        }
    }
    

    Source

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