Complete Guide to JavaScript Minification: Techniques and Best Practices
Learn everything about JavaScript minification: techniques, tools, best practices and impact on web performance.
Why minify your JavaScript?
JavaScript minification isn't just a technical optimization. It's a crucial element that directly impacts user experience, SEO, and infrastructure costs. In this article, we'll explore the real benefits of minification and show you how to implement professional solutions with Terser and UglifyJS.
Real-world performance impact
Here are real optimization data from an e-commerce project:
Before optimization
After optimization
Google uses Core Web Vitals as a ranking factor. Minification directly improves these metrics:
Setting up Terser
Terser is UglifyJS's successor, faster with better ES6+ support.
Installation
npm install --save-dev terserBasic configuration
const terser = require('terser');
const result = await terser.minify(code, {
compress: {
drop_console: true,
drop_debugger: true,
pure_funcs: ['console.log']
},
mangle: {
toplevel: true
}
});Custom NPM script
// package.json
{
"scripts": {
"build:js": "terser src/js/*.js -o dist/bundle.min.js",
"build:prod": "npm run build:js && npm run build:css"
}
}Optimal configuration for production environment with source maps and advanced optimizations.
Configuration
const terserConfig = {
compress: {
arguments: true,
booleans_as_integers: true,
drop_console: true,
drop_debugger: true,
ecma: 2020,
keep_infinity: true,
passes: 3,
pure_funcs: ['console.log', 'console.info'],
unsafe: true,
unsafe_arrows: true,
unsafe_comps: true,
unsafe_math: true
},
mangle: {
toplevel: true,
properties: {
regex: /^_/
}
},
format: {
comments: false,
ecma: 2020
},
sourceMap: {
filename: 'bundle.min.js',
url: 'bundle.min.js.map'
}
};Usage
const fs = require('fs');
const terser = require('terser');
async function minifyFile(inputPath, outputPath) {
const code = fs.readFileSync(inputPath, 'utf8');
const result = await terser.minify(code, terserConfig);
fs.writeFileSync(outputPath, result.code);
if (result.map) {
fs.writeFileSync(outputPath + '.map', result.map);
}
console.log(`Minified: ${inputPath} -> ${outputPath}`);
console.log(`Size reduction: ${((code.length - result.code.length) / code.length * 100).toFixed(1)}%`);
}Alternative with UglifyJS
UglifyJS remains a viable option, especially for older projects.
Installation
npm install --save-dev uglify-jsUglifyJS configuration
const UglifyJS = require('uglify-js');
const result = UglifyJS.minify(code, {
compress: {
drop_console: true,
drop_debugger: true,
pure_funcs: ['console.log']
},
mangle: true,
output: {
comments: false
}
});Webpack Integration
Professional integration in a modern Webpack workflow.
Configuration Webpack
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
mode: 'production',
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true,
pure_funcs: ['console.log']
},
mangle: {
toplevel: true
}
},
extractComments: false
})
]
}
};package.json
{
"scripts": {
"build": "webpack --mode=production",
"build:analyze": "webpack-bundle-analyzer dist/static/js/*.js"
},
"devDependencies": {
"terser-webpack-plugin": "^5.3.0",
"webpack-bundle-analyzer": "^4.9.0"
}
}Advanced techniques
Eliminate dead code and optimize imports for maximum minification.
Minimize the impact of polyfills on bundle size.
Before
import 'core-js/stable';
import 'regenerator-runtime/runtime';
// 50KB of loaded polyfillsAfter
// Conditional polyfills
if (!Array.prototype.includes) {
// Specific polyfill - 2KB
}
// On-demand loadingMonitoring and metrics
Monitor the impact of your optimizations with these tools:
Set up alerts to maintain performance.
Configuration GitHub Actions
// .github/workflows/performance.yml
name: Performance Check
on: [push]
jobs:
lighthouse:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Lighthouse CI
run: |
npm install -g @lhci/cli
lhci autorun --upload.target=temporary-public-storageConclusion
JavaScript minification isn't an option, it's a necessity. With the right practices and tools, you can significantly reduce your file sizes while improving user experience and SEO.
