JavaScript Minification Guide — Terser and Webpack

JavaScript Minification Guide — Terser and Webpack

How JS minification works: Terser setup, Webpack production config, tree-shaking notes, and when an online minifier is enough.

25.10.2025
8 min read
Share this article:
JavaScriptMinificationPerformanceOptimizationTutorial

What JavaScript minification gives you

JavaScript minification removes whitespace and comments and renames symbols to shrink files before they reach the browser. This guide covers Terser setup, a Webpack production configuration, and how tree shaking complements minification. It also says when a quick pass with an online JavaScript minifier is enough for smaller scripts.

JavaScript files typically 30 to 70% smaller before gzip
Less code to download and parse, which can bring First Contentful Paint (FCP) forward
Less bandwidth and CDN traffic
Faster loading, which helps Core Web Vitals such as LCP and INP
A smoother experience, especially on slow mobile connections

Performance impact

Example before and after

Figures from an e-commerce project, given as an illustration. Your results depend on your code, your dependencies and your server compression:

Performance dashboard showing before/after JavaScript minification metrics

Before optimization

File size
2.3 MB
Load time
3.2s
Bounce rate
68%
Conversion rate
2.1%

After optimization

File size
580 KB
Load time
1.8s
Bounce rate
42%
Conversion rate
3.7%
SEO impact

Google measures Core Web Vitals and uses them as page experience signals. Minification helps some of them and leaves the others unchanged:

LCP (Largest Contentful Paint): smaller scripts download sooner, which matters most when scripts delay rendering
INP (Interaction to Next Paint): less code to parse and run leaves the main thread free for interactions
CLS (Cumulative Layout Shift): no direct effect, because minification does not change the layout
TBT (Total Blocking Time, a lab metric): shorter parse and compile work means fewer long tasks

Setting up Terser

Basic installation and configuration

Terser is the JavaScript minifier Webpack 5 uses by default, and the one FastMinify runs. It continues uglify-es and handles modern ES6+ syntax.

Installation

npm install --save-dev terser

Basic 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" } }
Advanced configuration for production

A production configuration with source maps and extra passes. The unsafe options can change how code behaves; test the output before you ship it.

Terser and webpack configuration visualization with settings controls

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

Installation and usage

UglifyJS remains a viable option, especially for older projects.

Installation

npm install --save-dev uglify-js

UglifyJS 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

Webpack configuration with Terser

In production mode, Webpack 5 already minifies with Terser. The configuration below only sets the Terser options.

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

Tree shaking and dead code elimination

Remove dead code and import only what you use, so the minifier has less to process.

Use specific ES6 imports: `import { specificFunction } from 'library'`
Avoid wildcard imports: `import * as utils from 'utils'`
Configure Webpack for tree shaking
Mark side-effect-free calls with `/*#__PURE__*/` annotations
Polyfill optimization

Minimize the impact of polyfills on bundle size.

Before

import 'core-js/stable'; import 'regenerator-runtime/runtime'; // 50KB of loaded polyfills

After

// Conditional polyfills if (!Array.prototype.includes) { // Specific polyfill - 2KB } // On-demand loading

Monitoring and metrics

Measurement tools

Monitor the impact of your optimizations with these tools:

Bundle analyzer treemap visualization showing module sizes and dependencies
Lighthouse: performance audit in Chrome DevTools
WebPageTest: load tests from several locations and connection speeds
webpack-bundle-analyzer: treemap of what each bundle contains
Core Web Vitals report in Search Console: field data from real visits
Automated performance checks

Run Lighthouse CI on every push to follow performance over time. Add assertions in a Lighthouse CI configuration file if you want the build to fail on a regression.

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-storage

Conclusion

Minified JavaScript belongs in every production build. Configure Terser once, keep tree shaking in mind, and check the effect on Core Web Vitals after each release.

Add Terser to your build
Run Lighthouse CI on every push
Regularly measure impact on Core Web Vitals
Test on different devices and connections
Document your optimizations for the team
Share this article
Share this article: