Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass arguments to webpack.conf.js?

I'm following these instructions based on this project (the official Vue Webpack template).

This is what I did:

package.js:

"scripts": {
  "dev": "node build/dev-server.js",
  "dev-alt": "node build/dev-server.js && set arg=alt&&webpack"
},

webpack.base.config.js:

// npm run dev-alt in the terminal 
console.log('ARGS:', process.env.arg)

However ARGS: outputs undefined.

What the correct way to do this?

like image 832
alex Avatar asked Mar 14 '17 09:03

alex


2 Answers

With Webpack 5.x and above you can no longer pass custom arguments to Webpack like --myarg=val. But you can still pass the supported arguments like --mode=production.

So what's the solution for custom args? Instead we need to write it like this, using the new --env parameter.

  "build-project": webpack --mode=production --env myarg=val --env otherarg=val

Note that the custom arguments no longer start with -- after we put --env ahead of them. You'll need to put --env ahead of each custom key/value pair you need to define.


You'll also need to modify your Webpack config to export a function, rather than an object.

See this example code, taken from the docs.

const path = require('path');

module.exports = (env) => {
  // Use env.<YOUR VARIABLE> here:
  console.log('NODE_ENV: ', env.NODE_ENV); // 'local'
  console.log('Production: ', env.production); // true

  return {
    entry: './src/index.js',
    output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'dist'),
    },
  };
};
like image 167
Slbox Avatar answered Oct 16 '22 13:10

Slbox


Pass webpack arguments with --key=value in package.json

"scripts": {
 "build": "webpack --mode=production --browser=firefox",
}

Access argv in webpack.config.js like this

module.exports = (env, argv) => {
  if (argv.mode == "development") {
  }

  if (argv.browser == "firefox") {
  }
};
like image 5
GorvGoyl Avatar answered Oct 16 '22 13:10

GorvGoyl