Minify JavaScript — Reduce JS File Size
Learn how JavaScript minification works to reduce file size by removing whitespace, shortening variable names, and eliminating dead code. Includes Terser examples and best practices.
Detailed Explanation
How JavaScript Minification Works
JavaScript minification is the process of transforming human-readable source code into a smaller equivalent that behaves identically at runtime. A well-configured minifier can reduce JavaScript file sizes by 40-70% before compression.
What a Minifier Removes
A JavaScript minifier applies several transformations:
// Before minification
function calculateTotalPrice(items, taxRate) {
// Sum all item prices
let subtotal = 0;
for (let i = 0; i < items.length; i++) {
subtotal += items[i].price * items[i].quantity;
}
// Apply tax
const total = subtotal * (1 + taxRate);
return total;
}
After minification:
function calculateTotalPrice(t,a){let e=0;for(let l=0;l<t.length;l++)e+=t[l].price*t[l].quantity;return e*(1+a)}
Key Transformations
- Whitespace removal — All spaces, tabs, and newlines that are not syntactically required are stripped.
- Comment removal — Single-line (
//) and multi-line (/* */) comments are deleted. - Variable name mangling — Local variable and parameter names are shortened to single characters (
subtotalbecomese). Property names on objects are not mangled because they may be referenced externally. - Dead code elimination — Unreachable code paths and unused variables are removed.
- Constant folding — Expressions like
1 + 2are pre-computed to3. - Statement simplification —
return total;preceded byconst total = expr;collapses toreturn expr;.
Popular JavaScript Minifiers
- Terser — The de facto standard for ES6+ code, used by webpack, Vite, and Rollup.
- esbuild — Written in Go, extremely fast; handles both bundling and minification.
- SWC — Written in Rust, used by Next.js for production builds.
- UglifyJS — Legacy minifier for ES5; still used in older toolchains.
Unsafe Transformations to Watch
Minifiers offer aggressive optimizations that may break code:
- Top-level mangling can rename exports.
eval()andnew Function()rely on variable names at runtime.- Reliance on
Function.prototype.toString()breaks when names change.
Always test your minified output before deploying.
Use Case
JavaScript minification is essential for every production web application. Smaller JS bundles mean faster download times, quicker parsing by the browser, and improved Core Web Vitals scores — all of which directly impact user experience and SEO rankings.
Try It — Code Minifier
Related Topics
Beautify JavaScript — Format and Pretty-Print JS Code
JavaScript
JavaScript Whitespace Removal — Strip Unnecessary Spaces
JavaScript
Remove Code Comments — Strip Comments from JS, CSS, and HTML
Techniques
Production Build Minification — End-to-End Optimization
Production
Bundle Size Optimization — Reduce Total JavaScript Payload
Production