以下是我的webpack.config.js
的插件属性:
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production'),
}
}),
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
}),
new CompressionPlugin({
asset: '{file}',
algorithm: 'gzip',
regExp: /\.js$|\.html$/,
})
],
有时我想禁用CompressionPlugin
,有时我想启用它。但是,创建两个webpack配置文件看起来很笨拙。我想知道是否有办法使用命令行参数动态启用/禁用插件?
例如,如果我可以使用webpack --disable-compression-plugin
来禁用CompressionPlugin
,那就太棒了。有没有人对此有任何想法?
答案 0 :(得分:4)
尝试yargs
npm模块执行此操作:
npm install yargs --save-dev
在webpack.config.js
:
var webpack = require('webpack');
var yargs = require("yargs");
...
var argv = yargs
.boolean("disable-compression-plugin")
.argv;
...
// use argv.disableCompressionPlugin to check the option
module.exports = {
...
plugins: (function(argv) {
var plugins = [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production'),
}
}),
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
];
// HERE IS OPTION CONDITION
if (argv.disableCompressionPlugin) {
plugins.push(new CompressionPlugin({
asset: '{file}',
algorithm: 'gzip',
regExp: /\.js$|\.html$/,
}));
}
return plugins;
})(argv),
...
};
答案 1 :(得分:2)
只需命名插件:
module.exports = {
/.../
plugins: [
// enable by default
{ name: 'order', plugin: new webpack.optimize.OccurenceOrderPlugin() },
// enable by default
{ name: 'provide', plugin: new webpack.ProvidePlugin({ $: "jquery" }) },
// enable always
{ plugin: new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }) }
]
};
module.exports.plugins.forEach( function(p,i) {
if ( process.argv.indexOf( '--disable-' + p.name + '-plugin' ) === -1 ) {
module.exports.plugins[i] = p.plugin;
} else {
module.exports.plugins[i] = function() {}
}
});