Search code examples
webpackwebpack-2

How do i use a variable in my webpack.config file?


I am using webpack 2.2.1.

I want to define a variable on the command line, then use that variable in my build config.

So give a webpack command line that looks something like (or whatever it needs to be):

webpack "--output-path=..." "--env.wibble=NOMF"

How can I then write something like:

... 

const config = {
  entry: {
    ...
  },
  output: {
    ...
  },

  plugins: [
    ...
    new CopyWebpackPlugin([{
      from: '/somepath/' + env.wibble,
      to: 'something.js'
    }]),    
    ...
  ],

};

module.exports = config;

How can I define and use a variable in my build?

I'm intentionally not using NODE_ENV here (if I can).


Solution

  • The --env option is used to pass the defined properties to the webpack config, but for this to work you need to export a function that returns the configuration object, not the object itself.

    Your config would be:

    module.exports = function(env) {
      const config = {
        entry: {
          // ...
        },
        output: {
          // ...
        },
        plugins: [
          new CopyWebpackPlugin([{
            from: '/somepath/' + env.wibble,
            to: 'something.js'
          }]),    
        ],
      };
      return config;
    };
    

    You can shorten it by using an arrow function to implicitly return the object:

    module.exports = env => ({
      entry: {
        // ...
      },
      output: {
        // ...
      },
      plugins: [
        new CopyWebpackPlugin([{
          from: '/somepath/' + env.wibble,
          to: 'something.js'
        }]),    
      ],
    });
    

    See also Exporting a function to use --env.