tooling.report

feature

Minify JS

Can JavaScript be minified for production?

Person in shorts with blue hair walking left

Introduction

Minification is an important optimization step when bundling JavaScript code for production use. Minification reduces the size of code by removing comments and whitespace, inlining small functions and values where they are used, and normalizing control flow to use repeated syntax that compresses well.

The Test

This test ensures each build tool provides a way to enable minification for a production build.

index.js

import { logCaps } from './utils.js';
import { exclaim } from './exclaim.js';
logCaps(exclaim('This is index'));

exclaim.js

export function exclaim(msg) {
  return msg + '!';
}

utils.js

export function logCaps(msg) {
  console.log(msg.toUpperCase());
}

Bundling the above into a single output file should allow minification to be performed on the whole bundled code. In the most ideal scenario, a bundle should be produce that contains only the following code:

console.log('This is index!'.toUpperCase());

Conclusion

browserify

Browserify offers an uglifyify transform that will minify your code using terser.

parcel

Parcel minifies JavaScript using terser by default.

rollup

There are multiple plugins that can provide minification. This example uses terser.

webpack

Webpack defaults to production mode as of version 4, which enables optimizations including minification. It's recommended to explicitly indicate which mode Webpack should run in to ensure consistency via the command line -p and -d flags, or by setting the mode configuration option to "production" or "development". By default, Webpack minifies code using Terser with a set of conservative defaults, avoiding some optimizations that would break commonly used syntax.

One area where Webpack's output minification could be improved is that Terser's scope analysis cannot cross the module boundaries present in Webpack bundles, which includes the runtime. This means that, while a bundle may not actually use parts of a module or Webpack's runtime, Terser cannot infer this and the code is not removed. The impact of this on Webpack's runtime code is primarily a fixed cost since there is only one runtime, however the impact on bundled modules is less clear.