Since webpack 4, the production output gets minified using terser by default. Terser is an ES2015+ compatible JavaScript-minifier. Compared to UglifyJS, the earlier standard for many projects, it's a future-oriented option.
Although webpack minifies the output by default, it's good to understand how to customize the behavior should you want to adjust it further or replace the minifier.
The point of minification is to convert the code into a smaller form. Safe transformations do this without losing any meaning by rewriting code. Good examples of this include renaming variables or even removing entire blocks of code based on the fact that they are unreachable (if (false)
).
Unsafe transformations can break code as they can lose something implicit the underlying code relies upon. For example, Angular 1 expects specific function parameter naming when using modules. Rewriting the parameters breaks code unless you take precautions against it in this case.
In webpack, minification process is controlled through two configuration fields: optimization.minimize
flag to toggle it and optimization.minimizer
array to configure the process.
To tune the defaults, we'll attach terser-webpack-plugin to the project so that it's possible to adjust it.
To get started, include the plugin to the project:
npm add terser-webpack-plugin --develop
To attach it to the configuration, define a part for it first:
webpack.parts.js
const TerserPlugin = require("terser-webpack-plugin");
exports.minifyJavaScript = () => ({
optimization: { minimizer: [new TerserPlugin()] },
});
Hook it up to the configuration:
webpack.config.js
const productionConfig = merge([
parts.minifyJavaScript(),
...
]);
If you execute npm run build
now, you should see result close to the same as before.
Source maps are disabled by default. You can enable them through the `sourceMap` flag. You should check **terser-webpack-plugin** documentation for further options.
To adjust Terser behavior, attach `terserOptions` with the related options to the plugin.
Specific solutions allow you to preprocess code so that it will run faster. They complement the minification technique and can be split into scope hoisting, pre-evaluation, and improving parsing. It's possible these techniques grow overall bundle size sometimes while allowing faster execution.
Since webpack 4, it applies scope hoisting in production mode by default. It hoists all modules to a single scope instead of writing a separate closure for each. Doing this slows down the build but gives you bundles that are faster to execute. Read more about scope hoisting at the webpack blog.
Set `stats.optimizationBailout` flag as `true` to gain debugging information related to hoisting results.
If you consume HTML templates through your code using html-loader, you can preprocess it through posthtml with posthtml-loader. You can use posthtml-minifier to minify your HTML through it and posthtml-minify-classnames to reduce the length of class names.
css-minimizer-webpack-plugin is a plugin-based option that applies a chosen minifier on CSS assets. Using MiniCssExtractPlugin
can lead to duplicated CSS given it only merges text chunks. css-minimizer-webpack-plugin avoids this problem by operating on the generated result and thus can lead to a better outcome. The plugin uses cssnano underneath.
To get started, install css-minimizer-webpack-plugin first:
npm add css-minimizer-webpack-plugin --develop
Like for JavaScript, you can wrap the idea in a configuration part:
webpack.parts.js
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
exports.minifyCSS = ({ options }) => ({
optimization: {
minimizer: [
new CssMinimizerPlugin({ minimizerOptions: options }),
],
},
});
To override **cssnano** with another option, use the `minify` option. It accepts a function with the signature `(data, inputMap, minimizerOptions) =>`.
Then, connect with the main configuration:
webpack.config.js
const productionConfig = merge([
parts.minifyJavaScript(),
parts.minifyCSS({ options: { preset: ["default"] } }),
...
]);
If you build the project now (npm run build
), you should notice that CSS has become smaller as it's missing comments and has been concatenated:
⬡ webpack: Build Finished
⬡ webpack: assets by path *.js 129 KiB
asset vendor.js 126 KiB [emitted] [minimized] (name: vendor) (id hint: commons) 2 related assets
asset main.js 3.32 KiB [emitted] [minimized] (name: main) 2 related assets
asset 34.js 247 bytes [emitted] [minimized] 2 related assets
asset main.css 730 bytes [emitted] (name: main)
...
webpack 5.5.0 compiled successfully in 6388 ms
Using [last-call-webpack-plugin](https://www.npmjs.com/package/last-call-webpack-plugin) is a more generic approach and you can use it to define which processing to use against which file format before webpack finishes processing.
Compression techniques, such as gzip or brotli, can be used to reduce the file size further. The downside of using additional compression is that it will lead to extra computation on the client side but on the plus side you save bandwidth.
Often the compression setup can be done on server-side. Using webpack, it's possible to perform preprocessing with compression-webpack-plugin.
To make it more tricky for third parties to use your code, use webpack-obfuscator. Although protecting code is difficult when it's shared with the client, the code can be made much harder to use.
Minification is the most comfortable step you can take to make your build smaller. To recap:
You'll learn to apply tree shaking against code in the next chapter.
This book is available through Leanpub (digital), Amazon (paperback), and Kindle (digital). By purchasing the book you support the development of further content. A part of profit (~30%) goes to Tobias Koppers, the author of webpack.