I have a simple webpack.config.js
module.exports = {
entry: \"./app.js\",
output: {
filename: \"bundle.js\"
},
}
And I want to p
webpack.config.js
can also exports a function of env which can return a conf object. You can therefore have a webpack config like:
module.exports = env => {
return {
entry: env === "production" ? "./app.js": "app-dev.js",
output: {
filename: "bundle.js"
},
}
};
and then call webpack from command-line (or package.json) like this:
webpack --env=production
You may use argv package and set the variables. You must do it before module.export
.
The easiest way, in my opinion, to pass arguments is to use Node. Webpack being the one receiving the arguments, you can save your command line arguments in a dedicated environment variable (which exists only within the session):
// webpack.config.js
process.env.MY_APPLICATION_NAME_ARGS = JSON.stringify(process.argv)
export default {
...
Then in your main.js (anywhere where you want to parse them), you retrieve your command line arguments from your dedicated environment variable.
// main.js
const myArgs = JSON.parse(env.MY_APPLICATION_NAME_ARGS )
As you'll be retrieving all of the arguments you passed to Webpack, using this, you'll be able to use any node modules (like yargs for instance) painlessly to parse them (or do it manually of course).
So you'll be able to do things like these without any issues:
webpack ... --opt1 the_value --custom1 something
yarn run dev --opt1 the_value --custom1 something
etc.
You can provide custom parameters on the env
variable from the command line, so for this example you could call:
webpack --env.entry='./app.js' --env.output='bundle.js'
and use them in your webpack by doing
module.exports = env => ({
entry: env.entry,
output: {
filename: env.output
},
});