webpack 命令行 传入自定义变量

时间:2023-03-09 23:43:01
webpack 命令行 传入自定义变量

https://github.com/webpack/webpack/issues/2254

--env 变量

Yes this is intended. Custom argumens can be passed via --env prefix, i. e. --env.compress. Than export a function from the webpack.config.js and it's called with the env parameter.

module.exports = function(env) {
// ...
if (env.compress === 'true') {
var CompressionPlugin = require('compression-webpack-plugin');
config.plugins.push(
new CompressionPlugin({
asset: '{file}',
algorithm: 'gzip',
regExp: /\.js$|\.html$/
}))
}
}

通过 argv 访问

In Webpack 1.x, I can pass in my own command line arguments like this:

webpack --config ./webpack.config.prod.js --compress true

Here --compress is the custom command line arguments, it can be used like this in the webpack.config.js:

var argv = require('yargs').argv;

if (argv.compress === 'true') {
var CompressionPlugin = require('compression-webpack-plugin');
config.plugins.push(
new CompressionPlugin({
asset: '{file}',
algorithm: 'gzip',
regExp: /\.js$|\.html$/
}))
}