How to build minified and uncompressed bundle with webpack?
webpack.config.js:
const webpack = require("webpack");
module.exports = {
entry: {
"bundle": "./entry.js",
"bundle.min": "./entry.js",
},
devtool: "source-map",
output: {
path: "./dist",
filename: "[name].js"
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
minimize: true
})
]
};
Since Webpack 4, webpack.optimize.UglifyJsPlugin
has been deprecated and its use results in error:
webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead
As the manual explains, the plugin can be replaced with minimize
option. Custom configuration can be provided to the plugin by specifying UglifyJsPlugin
instance:
const webpack = require("webpack");
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
// ...
optimization: {
minimize: true,
minimizer: [new UglifyJsPlugin({
include: /\.min\.js$/
})]
}
};
This does the job for a simple setup. A more effective solution is to use Gulp together with Webpack and do the same thing in one pass.
You can use a single config file, and include the UglifyJS plugin conditionally using an environment variable:
const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
const PROD = JSON.parse(process.env.PROD_ENV || '0');
module.exports = {
entry: './entry.js',
devtool: 'source-map',
output: {
path: './dist',
filename: PROD ? 'bundle.min.js' : 'bundle.js'
},
optimization: {
minimize: PROD,
minimizer: [
new TerserPlugin({ parallel: true })
]
};
and then just set this variable when you want to minify it:
$ PROD_ENV=1 webpack
Edit:
As mentioned in the comments, NODE_ENV
is generally used (by convention) to state whether a particular environment is a production or a development environment. To check it, you can also set const PROD = (process.env.NODE_ENV === 'production')
, and continue normally.
To add another answer, the flag -p
(short for --optimize-minimize
) will enable the UglifyJS with default arguments.
You won't get a minified and raw bundle out of a single run or generate differently named bundles so the -p
flag may not meet your use case.
Conversely the -d
option is short for --debug
--devtool sourcemap
--output-pathinfo
My webpack.config.js omits devtool
, debug
, pathinfo
, and the minmize plugin in favor of these two flags.
You can run webpack twice with different arguments:
$ webpack --minimize
then check command line arguments in webpack.config.js
:
var path = require('path'),
webpack = require('webpack'),
minimize = process.argv.indexOf('--minimize') !== -1,
plugins = [];
if (minimize) {
plugins.push(new webpack.optimize.UglifyJsPlugin());
}
...
example webpack.config.js