在Webpack中,如何根据命令行参数启用插件?

以下是我的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而有时我想启用它。 但是,创build两个webpackconfiguration文件看起来很笨拙。 我想知道是否有办法通过使用命令行参数dynamic地启用/禁用插件?

例如,如果我可以使用webpack --disable-compression-plugin来禁用CompressionPlugin ,那将是非常好的。 有没有人有任何想法呢?

试试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), ... }; 

只是名字插件:

 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() {} } });