Introduction
Terser picks up where UglifyJS left off, providing a JavaScript parser, mangler, and compressor that fully supports ES2015+ syntax. It is the default minifier used by Webpack 5, Vite, Rollup, and most modern JavaScript build tools.
What Terser Does
- Parses ES6+ JavaScript into an AST for analysis and transformation
- Compresses code by removing dead branches, inlining constants, and simplifying expressions
- Mangles variable and function names to short identifiers for smaller output
- Generates source maps to maintain debuggability after minification
- Supports top-level and per-function configuration for compress and mangle passes
Architecture Overview
Terser processes JavaScript in three phases: parsing (source to AST using its own parser), compressing (AST-to-AST transformations that reduce code size), and output (AST to minified string with optional source map). The compressor applies multiple passes, each running a set of optimization rules like dead code elimination, constant folding, and function inlining. The mangler then renames local variables to short names, respecting scopes and reserved words.
Self-Hosting & Configuration
- Install via npm:
npm install terser(library) ornpm install -g terser(CLI) - Use the CLI:
terser input.js --compress --mangle -o output.min.js - Use the API:
const { minify } = require('terser'); await minify(code, options) - Configure compress options:
{ dead_code: true, drop_console: true, passes: 2 } - Generate source maps:
--source-map "url=output.min.js.map"
Key Features
- Full ES2015+ support including async/await, optional chaining, and nullish coalescing
- Multi-pass compression finds additional optimization opportunities on each pass
- Tree-shaking-friendly output preserves module structure for downstream bundlers
- Property mangling with
--mangle-propsfor aggressive size reduction - Configurable per-function annotations like
/*@__PURE__*/for side-effect-free marking
Comparison with Similar Tools
- esbuild — much faster but with fewer compression optimizations; Terser produces smaller output
- SWC minifier — Rust-based and faster; Terser has more mature compression heuristics
- UglifyJS — Terser's predecessor, limited to ES5 syntax only
- Google Closure Compiler — more aggressive optimizations but requires type annotations for best results
FAQ
Q: Why use Terser instead of esbuild for minification? A: Terser typically produces 5-15% smaller bundles due to its multi-pass compressor and advanced dead code elimination, at the cost of slower build times.
Q: Does Terser handle TypeScript?
A: No. Terser works on JavaScript output. Run TypeScript through tsc or a transpiler first, then minify the JavaScript with Terser.
Q: Can I keep certain variable names from being mangled?
A: Yes. Use mangle: { reserved: ['myVar', 'jQuery'] } to protect specific names.
Q: Is Terser used by Webpack?
A: Yes. Webpack 5 uses terser-webpack-plugin as its default JavaScript minimizer.