All articles

JavaScript minification with Terser

· 3 min read

Minified JavaScript downloads faster and is also faster to parse. Every production bundler minifies by default, but knowing what the minifier does helps when output breaks, when bundles are bigger than expected, or when you need to configure it.

Three kinds of transformation

Terser is one of the most widely used minifiers, and its work falls into three groups:

  1. Whitespace and comments: removed, except license comments (/*! ... */ or containing @license by default).
  2. Compress: rewrites code into shorter equivalents and removes code that can't run.
  3. Mangle: renames local variables and function parameters to short names.
// Input
function calculateTotal(items, taxRate) {
  const DEBUG = false;
  let subtotal = 0;
  for (const item of items) {
    subtotal += item.price * item.quantity;
  }
  if (DEBUG) console.log("subtotal", subtotal);
  return subtotal * (1 + taxRate);
}
// Output (compress + mangle)
function calculateTotal(t,c){let n=0;for(const c of t)n+=c.price*c.quantity;return n*(1+c)}

The DEBUG branch is gone because the constant is false. Local names are shortened, and the loop variable even reuses the name c, which is safe because it lives in its own block scope. The function name stays because it's a top-level declaration that other scripts might reference.

Compress options that matter

import { minify } from "terser";

const result = await minify(code, {
  compress: {
    passes: 2,               // run compress twice for slightly smaller output
    drop_console: true,      // remove console.* calls
    pure_funcs: ["debug"],   // treat these calls as removable if the result is unused
  },
  mangle: true,
  module: true,              // ES module: top-level names are private, so they can be mangled too
  sourceMap: { url: "app.min.js.map" },
});
  • drop_console removes every console.* call, including console.error. Use pure_funcs: ["console.log", "console.debug"] to remove only some.
  • module: true enables top-level mangling and strict mode assumptions for ES modules. Bundlers set it for you.
  • passes above 1 gives small extra savings at the cost of build time.
  • ecma lets Terser use newer syntax in the output (like arrow functions) when your targets support it.

Mangle and what it can't rename

Mangling is safe for local variables because nothing outside the function can see them. It doesn't touch:

  • Global variables and top-level declarations in scripts (unless toplevel or module is set).
  • Property names (item.price stays item.price).
  • Names in eval or with scopes, where Terser can't know what's referenced.

Property mangling (mangle: { properties: true }) exists, but it breaks any code that accesses those properties by string, including JSON from APIs. Only use it with a strict naming convention like { regex: /^_/ }.

Code that depends on names

class UserService {}
console.log(new UserService().constructor.name); // 'UserService', or 'e' after mangling

Frameworks that use class or function names for dependency injection or debugging need keep_classnames: true or keep_fnames: true.

Dead code and side effects

Tree shaking in the bundler removes unused exports; Terser removes unreachable code inside what remains. Both need to know which calls have side effects. Bundlers recognize this annotation:

export const theme = /*#__PURE__*/ createTheme({ primary: "blue" });

If theme is never imported, the call is removed. "sideEffects": false in a library's package.json tells bundlers whole files can be dropped.

Source maps

Minified code produces stack traces like TypeError at e (app.min.js:1:4821). A source map lets DevTools and error trackers translate that back to the original file and line. Generate maps in every production build; you can upload them to your error tracker without serving them publicly.

Minify in your build

You rarely call Terser directly:

Tool Default minifier Switch
Vite esbuild build.minify: "terser" (install terser)
webpack 5 Terser (TerserWebpackPlugin) optimization.minimizer
Next.js SWC Built in
Rollup none @rollup/plugin-terser
esbuild itself --minify

Checking the result

  1. Compare sizes before and after compression; the same measuring approach works for JS.
  2. Inspect what's in the bundle with vite-bundle-visualizer, webpack-bundle-analyzer or source-map-explorer. Large dependencies usually matter more than minifier settings.
  3. Run your tests against the production build at least once, to catch name-dependent code.

Stylesheets go through a similar process; see how to minify CSS.

Frequently asked questions

Is minified JavaScript secure or obfuscated?

No. Minification makes code smaller, not secret. Anyone can format it again and read the logic. Never put secrets in client-side code.

Terser, esbuild or SWC?

esbuild and SWC are much faster and are the defaults in many bundlers. Terser often produces slightly smaller output and has the most options. For most apps the size difference is small.

Why does my code break only after minification?

Usually because it depends on function or class names (fn.name, constructor.name), on property names accessed as strings, or on side effects a pure annotation hid. Use keep_fnames or keep_classnames, or remove the dependency.

Should I minify Node.js server code?

It's rarely useful: download size doesn't matter on servers, and readable stack traces do. Bundling can still help cold starts for serverless functions.

Further reading