JavaScript Minifier

Minify JavaScript by removing whitespace and comments

100% client-side ยท your data never leaves your browser
0 characters โ€ข 0 lines
โš ๏ธ Important Note

This is a basic JavaScript minifier that removes comments and whitespace. It does NOT perform advanced optimizations like variable renaming, dead code elimination, or scope analysis.

For production use: Use professional tools like Terser, UglifyJS, or build tools (Webpack, Vite, Rollup) with proper minification plugins for safe and optimal results.

โ„น๏ธ About JavaScript Minification

JavaScript minification reduces file size by removing whitespace, comments, and (in advanced minifiers) renaming variables to shorter names. This improves load times and reduces bandwidth usage.

๐Ÿ“– How to Use

  1. Paste or type your JavaScript in the input field
  2. Click "Minify JavaScript" to compress the code
  3. View the compression percentage to see space saved
  4. Click "Copy" to copy the minified JavaScript to your clipboard
  5. Important: Test the minified code before using in production

About the JavaScript Minifier

The JavaScript Minifier is a free, browser-based tool designed to optimize JavaScript code for web performance by removing whitespace, comments, and unnecessary characters. While this tool provides basic minification suitable for quick testing and small projects, production applications should use professional minifiers like Terser or UglifyJS integrated into build pipelines for advanced optimizations including variable mangling, dead code elimination, and AST-based transformations. Perfect for developers who need instant JavaScript compression without installing tools, understanding build configurations, or setting up complex workflows. All processing happens locally in your browser - no code is transmitted to servers, ensuring complete privacy for proprietary JavaScript.

Key Features:

  • Real-time minification with instant compression percentage display
  • 100% client-side processing - your JavaScript never leaves your browser
  • No registration, login, or installation required
  • Removes whitespace, comments, and unnecessary semicolons
  • One-click copy to clipboard for workflow integration
  • Handles medium-sized JavaScript files efficiently
  • Mobile-friendly responsive interface for on-the-go optimization
  • Compare with professional tools before production deployment

Common Use Cases:

  • Quick Testing: Test JavaScript minification impact before integrating Terser or UglifyJS into your build pipeline
  • Small Script Optimization: Minify inline scripts, bookmarklets, or small utility functions for email signatures or documentation and use our Hash Generator to create integrity checksums for minified files (also see our CSS Minifier for stylesheet optimization)
  • Code Snippet Sharing: Minify JavaScript snippets before sharing in forums, Stack Overflow, or code examples
  • Learning Tool: Understand the impact of minification on code size before implementing production build tools
  • Legacy Code Compression: Quickly compress old JavaScript files that don't have build tool integration

JavaScript Minification Examples & Implementation

UglifyJS vs Terser Comparison

// Original ES6+ code (385 bytes):
const getUserData = async (userId) => {
  const response = await fetch(`/api/users/$${userId}`);
  const data = await response.json();
  return data;
};

class UserManager {
  constructor(apiUrl) {
    this.apiUrl = apiUrl;
  }

  async getUser(id) {
    return await getUserData(id);
  }
}

// UglifyJS (doesn't support ES6+ without transpilation):
// ERROR: Unexpected token: keyword ยซconstยป

// Terser output (142 bytes - 63% smaller):
const getUserData=async e=>{const t=await fetch(`/api/users/$${e}`);return await t.json()};class UserManager{constructor(e){this.apiUrl=e}async getUser(e){return await getUserData(e)}}

Use case: Use Terser for modern JavaScript (ES6+) with better compression and ES module support

Webpack Production Configuration

// webpack.config.js - Production minification:
const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
  mode: 'production',
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          compress: {
            drop_console: true,  // Remove console.log
            passes: 2,           // Multiple optimization passes
            dead_code: true,
            unused: true
          },
          mangle: {
            safari10: true,      // Safari 10 compatibility
          },
          format: {
            comments: false,     // Remove all comments
          }
        },
        extractComments: false,  // Don't extract comments to separate file
      }),
    ],
  },
  output: {
    filename: '[name].[contenthash].min.js'
  }
};

// Result: app.a3f2c1b.min.js (45% smaller than source)

Use case: Configure Webpack with Terser for production builds with aggressive minification

Library Distribution with Variable Mangling

// Original library code (1.2KB):
export function validateEmail(email) {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

export function validatePassword(password) {
  const minLength = 8;
  const hasUpperCase = /[A-Z]/.test(password);
  const hasLowerCase = /[a-z]/.test(password);
  const hasNumber = /\d/.test(password);
  return password.length >= minLength && hasUpperCase && hasLowerCase && hasNumber;
}

// Terser with conservative mangling (preserve exports):
// terser lib.js -o lib.min.js -c -m reserved=['validateEmail','validatePassword']

// Output (0.5KB - 58% smaller):
export function validateEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}export function validatePassword(e){const a=/[A-Z]/.test(e),s=/[a-z]/.test(e),t=/\d/.test(e);return e.length>=8&&a&&s&&t}

Use case: Minify libraries while preserving public API function names using reserved keywords

ES6+ Module with Tree Shaking

// utils.js - Multiple exports (5KB total):
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
export const multiply = (a, b) => a * b;
export const divide = (a, b) => a / b;
// ... 50 more utility functions

// app.js - Only import what you need:
import { add } from './utils.js';

console.log(add(2, 3));

// Webpack/Rollup with tree shaking + Terser:
// 1. Tree shaking removes unused exports (subtract, multiply, divide, etc.)
// 2. Terser minifies the remaining code

// Final bundle (0.2KB - 96% smaller):
console.log(2+3);

// Dead code elimination optimized away the function entirely!

Use case: Combine ES6 modules with tree shaking and minification for dramatic size reduction

Source Map Generation

// Generate source maps with Terser CLI:
terser app.js -o app.min.js -c -m --source-map "url='app.min.js.map'"

// app.min.js (minified with source map reference):
function e(e,t){return e+t}console.log(e(2,3));
//# sourceMappingURL=app.min.js.map

// app.min.js.map (mapping file):
{
  "version": 3,
  "sources": ["app.js"],
  "names": ["add","a","b","console","log"],
  "mappings": "AAAA,SAASA,EAAIC,EAAGC,GAAK,OAAOD,EAAIC,CAE9BC,QAAQC,IAAIJ,EAAI,EAAG,IAClB"
}

// Browser DevTools show original code with proper variable names:
// function add(a, b) { return a + b; }
// console.log(add(2, 3));

Use case: Generate source maps to debug production JavaScript with original code structure

Vite with esbuild Minification

// vite.config.js - Lightning-fast minification:
import { defineConfig } from 'vite';

export default defineConfig({
  build: {
    minify: 'esbuild',  // 10-100x faster than Terser
    target: 'es2015',
    rollupOptions: {
      output: {
        entryFileNames: 'assets/[name].[hash].min.js',
        manualChunks: {
          vendor: ['react', 'react-dom']  // Separate vendor bundle
        }
      }
    }
  }
});

// Build output:
// dist/assets/app.a3f2c1b.min.js (your code, minified)
// dist/assets/vendor.8e9f2d1.min.js (dependencies, minified)

// Performance:
// - esbuild: 0.5 seconds to minify
// - Terser: 5 seconds to minify (same codebase)
// - Compression: both achieve ~50% reduction

Use case: Use Vite with esbuild for extremely fast development builds and minification

โ“ Frequently Asked Questions

What is JavaScript minification and how does it work?

JavaScript minification is the process of transforming JavaScript code to reduce file size while maintaining identical functionality. Basic minification removes whitespace, comments, and line breaks. Advanced minifiers like Terser and UglifyJS parse JavaScript into an Abstract Syntax Tree (AST) - a structural representation of the code - which allows safe transformations. These transformations include variable name mangling (renaming variables to single letters like a, b, c), property mangling, dead code elimination, constant folding, and expression simplification. The AST approach ensures transformations are semantically correct and won't break code logic. Minification typically reduces JavaScript file size by 30-60%, with advanced techniques achieving up to 80% reduction when combined with tree-shaking and compression algorithms like gzip or brotli.

Why is JavaScript minification critical for web performance?

JavaScript minification directly impacts critical web performance metrics that affect user experience and SEO. Smaller JavaScript bundles reduce parse time, compilation time, and execution time in browsers - especially important for mobile devices with limited CPU power. Minified JavaScript improves Time to Interactive (TTI), First Input Delay (FID), and Total Blocking Time (TBT), all key Core Web Vitals metrics that Google uses for search rankings. For single-page applications (SPAs), JavaScript often represents 50-80% of total page weight. Minifying a 500KB bundle to 250KB saves users 250KB per page load - across millions of visitors, this translates to terabytes of bandwidth savings and significantly faster load times. Production JavaScript should always be minified as standard practice.

How do Terser and UglifyJS compare for production minification?

Terser and UglifyJS are both production-grade JavaScript minifiers, but Terser is the modern standard. UglifyJS was the industry leader for years but doesn't support ES6+ syntax (classes, arrow functions, async/await) without transpilation. Terser is a fork of UglifyJS-ES6 that fully supports modern JavaScript (ES2015+) and is actively maintained. Terser provides better compression ratios (5-15% smaller output), faster minification speeds, and supports source maps for debugging. Most modern build tools (Webpack 5+, Parcel, Rollup) use Terser by default. UglifyJS is still suitable for legacy ES5 codebases. For new projects, use Terser with maximum compression settings for optimal results. Both tools perform AST-based transformations including variable mangling, dead code removal, and expression optimization.

What is variable name mangling and is it safe?

Variable name mangling is the process of renaming local variables, function parameters, and function names to short identifiers (a, b, c, aa, ab, etc.) to reduce code size. Minifiers analyze the AST to identify which names can be safely renamed without breaking code. Local variables and function-scoped names are safe to mangle because they don't affect external code. However, mangling is NOT safe for: global variables, object properties accessed via strings, variables accessed via eval(), and exported function names in libraries. Professional minifiers like Terser have configurable mangling options - you can whitelist names to preserve (mangle.reserved) or enable property mangling with caution. Mangling can reduce file size by 10-30% but requires testing. Always test mangled code thoroughly before deploying to production.

What is dead code elimination and tree shaking?

Dead code elimination removes unreachable code that can never execute - like code after return statements, unused functions, and unreachable if-branches with constant conditions. Minifiers detect this during AST analysis and safely remove it. Tree shaking is a related but more powerful optimization performed by module bundlers (Webpack, Rollup) that analyzes ES6 imports/exports to remove unused exports from modules. For example, if you import only one function from a library with 100 functions, tree shaking removes the other 99. This can dramatically reduce bundle size - importing a single lodash function tree-shakes 99% of the library. Combine tree shaking (bundler-level) with dead code elimination (minifier-level) for maximum optimization. Use ES6 modules (import/export) instead of CommonJS (require) for effective tree shaking.

How do source maps help with debugging minified JavaScript?

Source maps are files (.js.map) that map minified code back to original source code, enabling developers to debug production issues with readable stack traces and breakpoints. When a minified file includes a source map reference (//# sourceMappingURL=bundle.min.js.map), browser DevTools automatically fetch and use it to display original code. Without source maps, debugging production errors shows minified variable names (e.g., function a(b,c)) which are impossible to understand. With source maps, you see the original function names and code structure. Source maps can be generated inline (embedded in the file), external (separate .map file), or hidden (uploaded to error tracking services like Sentry). For production, either omit source maps (smallest file size) or upload them to error tracking services for debugging without exposing source code publicly.

What compression levels should I use in Terser?

Terser offers configurable compression levels that balance file size reduction against minification time and safety. Level 1 (compress: false) only performs basic minification - whitespace and comment removal - with no AST transformations. Level 2 (compress: true, default settings) enables safe optimizations like dead code removal, constant folding, and basic mangling - suitable for most production use. Level 3 (compress: {passes: 2}, mangle: {properties: true}) enables aggressive optimizations including multiple optimization passes and property mangling - achieves maximum compression but requires thorough testing. For libraries, use conservative settings (mangle.reserved to preserve public API names). For applications, use aggressive settings for maximum size reduction. Typical configuration: {compress: {drop_console: true, passes: 2}, mangle: {safari10: true}, format: {comments: false}}. Always benchmark compression time vs size savings.

How do I integrate JavaScript minification into my build pipeline?

Modern build tools automatically minify JavaScript in production mode with minimal configuration. Webpack: set mode: "production" to enable TerserPlugin automatically, or configure optimization.minimizer for custom settings. Vite: automatically minifies with esbuild in production builds (extremely fast), or configure build.minify: "terser" for better compression. Rollup: use @rollup/plugin-terser in your plugins array. Parcel: automatically minifies in production with no configuration. Next.js/Astro: handle minification in their build pipelines automatically. For custom workflows, run Terser CLI (terser input.js -o output.min.js -c -m) or use gulp-terser/grunt-terser for Gulp/Grunt. Always set NODE_ENV=production to enable minification. Configure source maps, compression options, and output filenames in your build tool's config file for consistent, automated minification across all environments.

๐Ÿ”— Related Tools