Minification — What It Is, Principles and Tools for Code Minification

Author: IT Sectr Published: 2026-05-18 Reading time: 8 min

Minification is the process of removing all non-essential characters from source code: spaces, tabs, line breaks, and comments. Minification reduces the size of JavaScript, CSS, and HTML files without changing program execution logic. According to MDN Web Docs, minification can reduce file size by 50–70%, which directly affects application loading speed and First Contentful Paint (FCP).

Key Takeaways

  • Minification — removing spaces, line breaks, comments, and shortening variable names to reduce code size
  • Terser — the main JavaScript minification tool, successor to UglifyJS with ES6+ syntax support
  • esbuild — ultra-fast bundler and minifier written in Go, 10–100x faster than Webpack and Terser
  • Source maps — code maps that allow debugging minified code in its original form in the browser
  • CSS minification — removing spaces, shortening hex colors, and merging identical selectors in CSS

What is Minification?

Minification is an automatic transformation of source code that removes all characters that do not affect program execution. Spaces, tabs, newline characters, comments, and redundant parentheses are removed or shortened. Minification is applied to JavaScript, CSS, HTML, and, less frequently, JSON configurations before deployment to production.

The main goal of minification is to reduce the size of files transmitted over the network. A 300 KB JavaScript file after minification can take up 120–150 KB, which reduces loading time by 200–400 ms on a slow 3G connection. Google PageSpeed Insights and Lighthouse directly recommend minifying code: it is one of the criteria for performance evaluation and Core Web Vitals.

Minification is an integral part of the build pipeline. After transpilation with TypeScript or Babel, the code goes through Tree Shaking (removing unused functions), then through a minifier, and only then is assembled into the final bundle. In modern bundlers (Webpack, Rollup, esbuild), minification is performed by plugins at the final build stage.

What Minification Removes

ElementExample (before)Example (after)Savings
Spaces and tabslet x = 5;let x=5;~10–20%
Line breaks\n between linesall in one line~2–5%
Comments// commentremoved~5–30%
Redundant parenthesesif ((x > 0))if(x>0)~1–3%

How Minification Works: Main Techniques

Removing spaces and line breaks is the simplest and most obvious technique. The minifier parser traverses the AST (Abstract Syntax Tree) and removes all whitespace characters that are not part of string literals. Most minifiers additionally combine operators into a single line, which provides additional savings when compressing with GZip or Brotli.

Variable name replacement (mangling) is a more aggressive technique. Local variables and function parameters are renamed to single-letter identifiers: a, b, c. This reduces size by an additional 15–30%. Terser and esbuild support mangling with the option to preserve certain names (e.g., public API via mangle.props.reserved).

Dead Code Elimination

Dead code elimination (DCE) removes code branches that never execute. The minifier analyzes conditions that are always false (if (false)) and removes the corresponding blocks. More advanced analysis is performed at the Tree Shaking stage before minification, but DCE at the minifier level catches local cases of dead code not detected at the module level.

Variable Name Mangling

Mangling renames local variables and function parameters to short identifiers (one or two letters). Terser performs mangling based on scope: variables within a single function get unique short names that do not conflict with outer scopes. The mangle.reserved option allows preserving certain names — for example, public library APIs.

Mangling does not affect global variables, object properties (unless mangle.props is enabled), or class names used with new. To protect a library’s public API from mangling, use mangle.props.reserved with regular expressions: reserved: [“_prop”, /^private_/]. Without this setting, mangling can break a library if external code accesses object properties by name.

Example: Before and After Minification

js
// Source code
function calculateTotal(price, tax) {
    var result = price + (price * tax);
    // Return the total sum
    return result;
}

var total = calculateTotal(100, 0.2);
console.log(total);
js
// After Terser minification
function calculateTotal(a, b){return a + a * b}
var c = calculateTotal(100, .2);
console.log(c);

In the second example, Terser removed comments, spaces, and line breaks, renamed price to a, tax to b, result to c. The size decreased from 197 characters to 79 — a saving of 60%. At the same time, the code functionality is fully preserved: calculateTotal(100, 0.2) returns 120.

Minification Tools: Terser, esbuild, UglifyJS

Terser is the standard JavaScript minifier in the Webpack ecosystem and most modern bundlers. Terser supports ES6+ syntax (arrow functions, async/await, spread), mangling with public API protection, source maps, and parallel execution using CPU count. Since version 5.16, Terser includes TypeScript optimizations — removing type-only imports and interfaces.

esbuild is a minifier written in Go, embedded in the eponymous bundler. esbuild performs minification 10–100 times faster than Terser due to native code and parallel processing. However, esbuild supports fewer optimizations: it does not perform mangling with property preservation, does not remove type-only imports, and optimizes expressions less aggressively.

Terser Configuration in Webpack

js
// webpack.config.js — TerserPlugin configuration
const TerserPlugin = require("terser-webpack-plugin");

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          compress: {
            drop_console: true,
            drop_debugger: true,
            dead_code: true,
          },
          mangle: {
            reserved: ["React", "Component"],
          },
          output: {
            comments: false,
          },
        },
        parallel: true,
      }),
    ],
  },
};

The TerserPlugin configuration includes three key blocks. compress handles expression optimization: drop_console removes console.log, drop_debugger removes debugger, dead_code removes unreachable branches. mangle controls variable renaming with reserved to protect public names. parallel enables multithreading with CPU count.

CSS Minification with esbuild

js
// esbuild: CLI command for JS and CSS minification
// esbuild app.js --bundle --minify --outfile=dist/app.min.js
// esbuild app.css --bundle --minify --outfile=dist/app.min.css

const esbuild = require("esbuild");

esbuild.build({
  entryPoints: ["src/app.js", "src/styles.css"],
  bundle: true,
  minify: true,
  sourcemap: true,
  target: ["es2015"],
  outdir: "dist",
}).catch(() => process.exit(1));

The esbuild API accepts one-liner configuration. minify: true enables minification of both JS and CSS. sourcemap: true generates code maps for debugging. target defines the minimum ES level — esbuild automatically transpiles modern code for the selected version. esbuild is especially effective for projects where build time is critical: CI/CD pipelines, Hot Module Replacement, and rapid prototypes.

Minification in React Native and WebView

React Native uses Metro Bundler — its own bundler that includes Terser-based minification. In production mode, Metro automatically applies minification to the application’s JavaScript bundle. Minification configuration in Metro is set through metro.config.js in the transformer.minifierConfig section. Additionally, inline-require can be disabled to reduce bundle size on iOS.

WebView in mobile applications also benefits from minification. HTML, CSS, and JS loaded in WebView should be minified before being embedded in the application or loaded from the server. For local resources (Assets), minification is especially important — APK/IPA size directly affects installation conversion in app stores.

Hermes and Minification

Hermes is a JavaScript engine for React Native developed by Facebook. Hermes performs Ahead-of-Time (AOT) bytecode compilation, which reduces application startup time by 30–50%. For Hermes, JavaScript bundle minification is performed before bytecode compilation using Terser. Hermes supports its own HBC (Hermes Bytecode) format, but the JS minification stage remains necessary.

Metro Configuration for React Native

js
// metro.config.js — minification configuration
const defaultConfig = require("metro-config/src/defaults");

module.exports = require("metro-config").mergeConfig(
  defaultConfig,
  {
    transformer: {
      minifierConfig: {
        compress: {
          drop_console: true,
        },
        mangle: {
          safari10: true,
        },
      },
    },
  }
);

Metro with minifierConfig.drop_console removes all console.log from the React Native production bundle. The mangle.safari10 parameter prevents renaming identifiers that break Safari 10 (iOS 10). This is especially important for applications supporting older iPad and iPhone 5s devices with iOS 10/11.

How Minification Differs from Compression

Minification and compression (gzip, brotli) are different optimization stages. Minification works at the source code level and reduces the number of characters before sending to the server. Compression works at the transport protocol level and is applied by the server (nginx, Apache, CDN) when transmitting the file to the client. Minification reduces size before compression, which gives a double effect: gzip compresses already reduced data.

A 300 KB JavaScript file after minification — 120 KB, after gzip — 35–40 KB. If only gzip is applied to the non-minified file, the size will be 55–70 KB. Minification + gzip gives a 30–40% better result than gzip alone. Brotli (level 6) compresses an additional 15–20% more efficiently than gzip after minification.

MethodLevelFile SizeReduction
Original file300 KB0%
After minificationCode120 KB60%
After gzip (without minification)Transport65 KB78%
Minification + gzipCode + Transport38 KB87%
Minification + BrotliCode + Transport30 KB90%

Frequently Asked Questions

How is minification different from uglify?

UglifyJS is an outdated minification tool that does not support ES6+ syntax. Terser is a fork of UglifyJS with modern JavaScript support. All modern bundlers (Webpack 5, Rollup, esbuild) use Terser or their own minifiers, while UglifyJS is only used in legacy projects.

Does minification increase size due to source maps?

Source maps are separate .map files not included in the production bundle. The server should only serve source maps to authorized developers (via the Authorization header). In production, source maps are not loaded by the user’s browser, so they do not affect bundle size.

Can minification break code?

Risk of breakage exists with aggressive mangling that transforms object property names. If code accesses DOM elements through data-attributes or uses JSON strings for field naming, mangling can rename public properties. The solution is to exclude via mangle.reserved or disable mangling for certain namespaces.

Is CSS minification mandatory?

CSS minification provides less gain (15–25%) than JS minification, but is mandatory for Core Web Vitals compliance. CSS minifiers remove spaces, merge identical selectors, shorten hex colors (#ff0000 → #f00), and remove unused @keyframes. CleanCSS and esbuild are popular CSS minification tools.

How to debug minified code?

Source maps (.map files) link minified code to the original source. In Chrome DevTools and Safari Web Inspector, when source maps are enabled, original files are displayed. For proper operation, source maps should be uploaded to the server (even in production) and enabled through developer tools.

Summary

  • Minification — removing spaces, comments, and line breaks from code without changing logic to reduce file size
  • Terser — the main JavaScript minifier in the modern web with ES6+ support, mangling, and source maps
  • esbuild — ultra-fast minifier written in Go, 10–100x faster than Terser, with JS and CSS support
  • React Native uses Metro Bundler with built-in Terser minification for production builds
  • Source maps are necessary for debugging minified code and should only be loaded for developers
  • Minification + gzip/Brotli provides a double compression effect: code becomes 5–10 times smaller than the original

We will develop a mobile application turnkey

IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.

Discuss the project

Read also