In Webpack, I have the following plugins:
plugins: [
new ExtractTextPlugin(\'styles.css\'),
new webpack.optimize.UglifyJsPlugin({
com
You can use mode argument in webpack to pass development
/production
value to webpack config and then conditionally load plugins.
NPM Script:
"start": "webpack --watch --mode=development",
"build": "webpack --mode=production",
webpack.config.js:
module.exports = (env, argv) => {
console.log("mode: ", argv.mode);
const isDev = argv.mode === "development";
const pluginsArr = [new CleanWebpackPlugin()];
// load plugin only in development mode
if (isDev) {
pluginsArr.push(new ExtensionReloader({}));
}
return {
entry: {},
devtool: isDev ? "inline-source-map" : "", // generate source code only in development mode
plugins: pluginsArr,
output: {},
};
};
Without variables it will look like this:
plugins: [
new ExtractTextPlugin('styles.css'),
(TARGET === 'build') && new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
drop_console: true,
}),
].filter(function(plugin) { return plugin !== false; })
You can have one webpack config, built upon another, and add a few plugins (and/or change output names, etc) in the latter one:
This webpack.release.config.js makes use of a webpack.config (development version), but uses more plugins...
process.env.NODE_ENV = 'release';
const config = require('./webpack.config'),
webpack = require('webpack');
config.output.filename = 'app.min.js';
// use another plugin, compare to the basic version ←←←
config.plugins.push(new webpack.optimize.UglifyJsPlugin({
minimize: true
}));
module.exports = config;
Also see here for a full example.
You can use this new syntax which uses the spread operator
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css'
}),
...(prod ? [] : [new BundleAnalyzerPlugin()])
],
I push onto the plugins array given a condition in my webpack.config.js
var webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: {
...
},
output: {
...
},
module: {
rules: [
...
]
},
plugins: [
new ExtractTextPlugin('styles.css'),
]
};
if (TARGET === 'build') {
module.exports.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
drop_console: true,
}),
);
}
I think the cleanest way is to set up multiple builds. If your webpack.config.js
exports an array of config objects instead a single object, webpack will automatically do a build for each one. I have several different builds, so I define the shared the config as variables, loop over the factors that vary between builds, and within the loop use conditionals to check which build it is. For example:
let allConfigs = [];
let buildTypes = ['dev', 'optimized'];
buildTypes.forEach( (type) => {
let buildConfig = {};
// ... other config
buildConfig.plugins = [];
if (type === 'optimized') {
// add Uglify to plugins array
}
// ...other config
allConfigs.push(buildConfig);
});