Web Development
JavaScript Code Minification: A Practical Guide
How JS minification works, what optimizations are safe, source map best practices, and integrating minification into your build pipeline.
What the Minifier Actually Does
JavaScript minification operates on the AST (Abstract Syntax Tree), not on raw text. The parser builds a tree of the code, then the minifier applies transformations: removing dead code branches, renaming local variables to single letters, inlining constants, simplifying boolean expressions, and merging adjacent variable declarations. Whitespace and comments are removed as a final pass, not as the primary optimization.
Tree-Shaking vs Minification
Tree-shaking removes unused exports at the module level (dead code elimination). Minification compresses what remains. Both are necessary for optimal bundles. Webpack and esbuild handle tree-shaking during bundling; Terser handles minification as a post-processing step. Using one without the other leaves significant size savings on the table.
Source Maps Are Not Optional
Without a source map, production errors point to line 1, column 23456 of main.min.js. Generate a .map file, upload it to your error monitor (Sentry, Datadog, Rollbar), and keep it off the public server — source maps can expose your original source code to anyone who knows the URL. Some teams serve source maps only behind authentication to protect proprietary logic.