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?
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'),
},
};
};
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") {
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With