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:
- Whitespace and comments: removed, except license comments (
/*! ... */or containing@licenseby default). - Compress: rewrites code into shorter equivalents and removes code that can't run.
- 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_consoleremoves everyconsole.*call, includingconsole.error. Usepure_funcs: ["console.log", "console.debug"]to remove only some.module: trueenables top-level mangling and strict mode assumptions for ES modules. Bundlers set it for you.passesabove 1 gives small extra savings at the cost of build time.ecmalets 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
toplevelormoduleis set). - Property names (
item.pricestaysitem.price). - Names in
evalorwithscopes, 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
- Compare sizes before and after compression; the same measuring approach works for JS.
- Inspect what's in the bundle with
vite-bundle-visualizer,webpack-bundle-analyzerorsource-map-explorer. Large dependencies usually matter more than minifier settings. - 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.