Developer Tools

Free JavaScript Minifier Online

Minify JavaScript by removing whitespace and comments. Reduce bundle size without transpiling.

JavaScript Minification: What It Is and When to Use It

JavaScript minification is the process of removing characters from source code that are not required for execution — comments, whitespace, newlines, and indentation. The result is a smaller file that a browser downloads faster, parses faster, and executes identically to the original. Minification is one of the cheapest performance wins in web development: a script that takes 200 ms to download over a slow connection might take 120 ms after minification, with no changes to functionality or correctness.

What a Whitespace Minifier Does

This tool performs whitespace-only minification — the foundational layer of any JavaScript minifier:

  • Removes single-line comments — lines and trailing remarks starting with // are stripped entirely.
  • Removes block comments — everything between /* and */ is removed, including multi-line JSDoc blocks.
  • Collapses whitespace — multiple spaces, tabs, and blank lines are collapsed to the minimum required. A single space is preserved only where JavaScript syntax requires it (between two adjacent identifiers like return value or typeof x).
  • Preserves string content — whitespace inside string literals, template literals, and regular expressions is left exactly as written. The parser handles single quotes, double quotes, backtick template literals, and nested ${} expressions.

A 500-line, well-commented JavaScript file typically minifies from 12 KB to 7–8 KB — a 35–40% reduction with zero change in runtime behaviour.

Whitespace Minification vs. Full Minification

Production-grade minifiers like Terser, esbuild, and the Closure Compiler go further than whitespace removal:

  • Identifier mangling — renames local variables from descriptive names (userProfileData) to one-letter names (a). This is the biggest size win for logic-heavy code, often reducing file size by an additional 20–30% on top of whitespace removal.
  • Dead code elimination — removes code paths that can never execute: unreachable branches, constant-falsy conditionals, unused exports in module-aware bundlers.
  • Constant folding — evaluates constant expressions at compile time. const MS_PER_DAY = 24 * 60 * 60 * 1000 becomes const MS_PER_DAY = 86400000, saving one multiplication per page load.
  • Function inlining — small functions called once may be inlined at their call site, eliminating function-call overhead and enabling further optimisation.
  • Property key shortening — advanced tools can shorten long object keys if they control the full scope of access.

Full minification with mangling typically achieves 50–70% reduction on unminified source. Whitespace-only achieves 20–40%. The gap matters for large applications; for small scripts under 10 KB, whitespace-only minification is often sufficient and carries zero risk of behavioural change.

When to Use This Tool

Most modern projects use bundlers (Webpack, Vite, esbuild, Rollup) that minify automatically as part of npm run build. You rarely need to manually minify code that passes through a bundler. This tool is most useful for:

  • CDN-hosted scripts — a standalone utility script loaded from a <script> tag, outside the main bundle, where a build step would be disproportionate.
  • Bookmarklets — browser bookmarklets must be a single line of JavaScript. Minification compresses them to a manageable URL length. Prepend javascript: to the output and drag to your bookmarks bar.
  • Inline <script> blocks — scripts embedded directly in HTML for critical path rendering, analytics, or third-party snippet integration.
  • Quick size estimation — checking how much a file could save before committing to a full build-tool integration.
  • Legacy codebases — projects without a build step that serve raw JavaScript files directly.
  • Copy-paste snippets — condensing a code snippet to share in a chat, comment, or documentation.

How the Minifier Handles JavaScript Syntax

Minifying JavaScript correctly is harder than it looks because the same characters mean different things in different positions. Two cases that trip up naive implementations:

String literals// not a comment inside a string, regex, or template literal must not be stripped. This minifier uses a state machine that enters "string mode" when it encounters a quote and stays there until the matching closing quote, respecting escape sequences (\', \\", \\n).

Regex literals vs. division — the same / character starts a regex literal after operators and keywords (return /pattern/, = /pattern/) but is a division operator after values (count / 2, array.length / 2). This minifier tracks the last emitted identifier and checks it against the set of keywords that precede regex literals (return, typeof, void, delete, throw, new, in, instanceof, of, case) to make the distinction in O(1) per character.

Template literals — backtick strings may contain ${...} interpolations that themselves contain arbitrary JavaScript expressions, including nested template literals. The minifier tracks brace depth to correctly identify the end of each interpolation block.

Minifying for Bookmarklets

Bookmarklets are a perfect use case for a browser-based minifier. A bookmarklet is a browser bookmark whose URL is a javascript: URI. The URL must be a single unbroken line — no newlines, no comments. Paste your script, click Minify, prepend javascript: to the output, and drag it to your bookmarks bar:

// Before minification (multi-line, with comments)
javascript:(function() {
  // Highlight all external links on the page
  const links = document.querySelectorAll('a[href^="http"]');
  links.forEach(function(link) {
    link.style.outline = '2px solid red';
  });
})();

// After minification
javascript:(function(){const links=document.querySelectorAll('a[href^="http"]');links.forEach(function(link){link.style.outline='2px solid red';});})();

Minification and Source Maps

Minification makes debugging production errors harder because line numbers and variable names no longer match the source. Source maps solve this: a .map file links each position in the minified output back to the original source line and column. DevTools in Chrome and Firefox load source maps transparently, showing you the original unminified code even when debugging a production bundle.

This tool does not generate source maps. If you need source map support, use your project's build tool or the Terser CLI:

npx terser input.js --compress --mangle --source-map -o output.min.js

For Webpack, source maps are controlled by the devtool option in webpack.config.js. The 'source-map' value generates a full external source map; 'hidden-source-map' generates the file but does not reference it in the bundle (useful for error monitoring services like Sentry that upload source maps separately).

Measuring Minification Impact

Not all files benefit equally from minification. Variables affecting the gain:

  • Comment density — heavily commented code (JSDoc on every function, section headers, inline explanations) saves 10–20% from comment removal alone.
  • Indentation style — 4-space indentation on deeply nested code saves more than 2-space.
  • Identifier length — descriptive variable names like calculateUserSubscriptionExpiry save nothing from whitespace minification, but save significantly from mangling.
  • Already-minified input — if you paste code that is already minified (a vendor library, for example), this tool will produce no change.

The stats panel above the output shows original size, minified size, and percentage saved, giving you an immediate measure of the impact.

JavaScript Minifiers at a Glance

For automated, production-grade minification:

  • esbuild — the fastest JavaScript/TypeScript bundler and minifier. Used internally by Vite and many other build tools. Minification is near-instant even for large bundles. Run with esbuild input.js --minify --outfile=output.min.js.
  • Terser — the most configurable JavaScript minifier. Successor to UglifyJS. Default minifier in Webpack 5. Supports ES2015+ and has fine-grained control over what transformations to apply. Slower than esbuild but produces slightly smaller output.
  • SWC — Rust-based compiler/minifier, used by Next.js 12+ as its default minifier. TypeScript-native, very fast, drop-in replacement for Babel + Terser in many configurations.
  • Rollup + terser plugin — common for library authors who want full control over the output module format and bundle structure, with Terser handling the final size reduction.
  • Google Closure Compiler — the most aggressive minifier; its ADVANCED_OPTIMIZATIONS mode can dramatically reduce size but requires annotations and type safety. Used by Google for its own large-scale production code.

Tree Shaking vs. Minification

Two distinct techniques are often conflated: tree shaking and minification. They are complementary, not interchangeable.

Tree shaking removes entire exported functions and modules that are imported but never called. If you import import { debounce } from "lodash-es" but only use debounce, tree shaking drops all the other lodash functions from your bundle. It operates at the module graph level and requires ES module (import/export) syntax to work. CommonJS (require/module.exports) is not tree-shakeable.

Minification removes characters from the code that is actually included in the bundle. It does not remove unused exports — that is tree shaking's job.

In a typical Vite or Webpack build, tree shaking runs first (during bundling), then minification runs on the resulting bundle. Both steps are necessary for the smallest possible output.

Minification Best Practices

  • Always minify in production, never in development — minified code is nearly impossible to debug. Use unminified builds locally and let your CI/CD pipeline apply minification before deployment.
  • Preserve licence comments — some open-source licences require the copyright notice to remain in the distributed file. Terser preserves comments starting with /*! by default; configure other tools similarly.
  • Combine with GZIP or Brotli — server compression and minification compound. A file minified from 100 KB to 60 KB then Brotli-compressed might transfer as 14 KB — a 7× improvement over the original uncompressed. Most CDNs and hosting providers (Vercel, Netlify, Cloudflare) apply Brotli automatically.
  • Set appropriate cache headers — a minified, content-hashed file like main.a3f9c2.js can be cached indefinitely (Cache-Control: max-age=31536000, immutable). This makes minification a one-time cost per deploy, not per request.
  • Never edit minified output manually — treat it as a build artefact. Fix the source and re-minify.

FAQ

Common questions

What does the JavaScript minifier remove?

The minifier removes single-line comments (// ...), block comments (/* ... */), and all unnecessary whitespace — leading/trailing spaces, blank lines, and extra indentation. It preserves string literals, template literals, and regex patterns exactly as written. Variable names and logic are untouched.

Is the minified output functionally identical to the original?

Yes. The minifier is a whitespace-only compressor — it does not rename variables, reorder expressions, or optimise logic. The output executes identically to the input. The only change is the removal of characters that have no effect on runtime behaviour.

Does it handle template literals and regex patterns correctly?

Yes. Template literals (including ${} interpolations) and regular expressions are scanned character-by-character and emitted verbatim. Whitespace inside strings and patterns is never removed. The minifier uses a heuristic to distinguish regex literals from division operators, which works correctly for standard JavaScript patterns.

How much size reduction can I expect?

Whitespace-only minification typically reduces file size by 20–40% for human-written code. Production minifiers like Terser or esbuild also mangle variable names and eliminate dead code, reaching 50–70% for complex files. For already-minified code, no additional reduction is possible.

Should I minify before or after bundling?

Bundlers like Webpack, Vite, esbuild, and Rollup minify as part of their build pipeline — you rarely need to minify files manually. Use this tool when you have a standalone script (a CDN snippet, a bookmarklet, an inline script tag) that falls outside your main build process.

Is my code sent to a server?

No. All processing runs entirely in your browser using JavaScript. Your code is never uploaded, transmitted, or logged anywhere. The tool works offline and requires no network connection after the page loads.

What about source maps?

This tool does not generate source maps. Source maps link minified code back to the original for debugging — they are generated by production build tools (Webpack, esbuild, Vite) which embed the mapping information in a .map file. For debugging minified production code, use the source maps generated by your build tool.

Can I minify TypeScript with this tool?

No — this tool minifies JavaScript only. TypeScript must be compiled to JavaScript first (using tsc or a bundler). The compiled .js output can then be minified here. If your workflow uses esbuild or Vite, TypeScript compilation and minification happen together in the build step.

More in Developer Tools