2026-03-03•3 min read•by DevUtilz
JavaScript Minification Guide
JavaScriptPerformanceOptimizationTutorial
JavaScript Minification Guide
Minification reduces JavaScript file size by removing unnecessary characters without changing functionality.
What Gets Removed
- Whitespace (spaces, tabs, newlines)
- Comments
- Long variable names (renamed to shorter)
- Unused code (in some cases)
// Before (readable)
function calculateTotal(items) {
let total = 0;
// Add up all item prices
for (let i = 0; i < items.length; i++) {
total += items[i].price;
}
return total;
}
// After (minified)
function n(t){let e=0;for(let n=0;n<t.length;n++)e+=t[n].price;return e}
Popular Minifiers
1. Terser (ES6+)
import terser from 'terser';
const minified = await terser.minify(code, {
compress: true,
mangle: true,
format: { comments: false }
});
2. UglifyJS (older)
const UglifyJS = require('uglify-js');
const result = UglifyJS.minify(code);
3. esbuild (fastest)
import * as esbuild from 'esbuild';
await esbuild.minify({
entryPoints: ['input.js'],
minify: true,
outfile: 'output.min.js'
});
Build Tools Integration
Vite
// vite.config.js
export default defineConfig({
build: {
minify: 'terser',
terserOptions: {
compress: {
drop_console: true
}
}
}
});
Webpack
// webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [new TerserPlugin()]
}
};
Impact
| Original | Minified | Savings | |----------|----------|---------| | 100 KB | 40 KB | 60% | | 500 KB | 200 KB | 60% | | 1 MB | 400 KB | 60% |
Savings depend on:
- Code style (more whitespace = more savings)
- Variable names (longer = more savings)
- Comments (more = more savings)
Gzip + Minification
// Before minification: 100KB
// After minification: 40KB
// After gzip: ~12KB (additional 70% compression)
Source Maps
// Generate source map for debugging
const minified = await terser.minify(code, {
sourceMap: {
filename: 'app.js',
url: 'app.min.js.map'
}
});
Common Options
const options = {
compress: {
dead_code: true, // Remove unreachable code
drop_console: true, // Remove console.* calls
unused: true // Remove unused functions
},
mangle: {
toplevel: true // Mangle top-level names
},
format: {
comments: false // Remove all comments
}
};
Testing Minified Code
// Test both versions produce same output
const original = originalFunction(input);
const minified = minifiedFunction(input);
console.assert(
JSON.stringify(original) === JSON.stringify(minified),
'Functions produce different results'
);
Best Practices
- Use build tools - Don't minify manually
- Keep source maps - For debugging production issues
- Test after minification - Catch minification bugs
- Combine with gzip/brotli - Maximum compression
- Consider tree shaking - Remove unused exports
Conclusion
Minification is essential for production. Use build tools like Vite, Webpack, or Rollup which include minification. Always test after minifying to catch bugs.