Terser

5.46.1 · active · verified Sun Apr 19

Terser is a powerful JavaScript parser, mangler, and compressor toolkit designed for modern ECMAScript (ES6+). It currently stands at version 5.46.1 and is under active development, serving as the maintained successor to the now-abandoned `uglify-es` project and `uglify-js` (which lacks ES6+ support). Terser largely retains API and CLI compatibility with its predecessors, making it a familiar choice for developers. Key differentiators include its robust support for modern JavaScript syntax and ongoing maintenance, addressing the limitations of older minifiers. While `terser` previously offered beautification features, these are being removed in favor of dedicated tools like Prettier. The project recommends using it in conjunction with bundlers like RollupJS for optimal output size.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to programmatically minify a JavaScript string using `terser`, including compression and mangling options for ES2020 syntax.

import { minify } from 'terser';

const code = `
class Greeter {
  constructor(name) {
    this.name = name;
  }

  greet() {
    return 'Hello, ' + this.name + '!';
  }
}

const greeter = new Greeter('World');
console.log(greeter.greet());
`;

async function runMinification() {
  try {
    const result = await minify(code, {
      compress: {
        dead_code: true,
        drop_console: true,
        ecma: 2020
      },
      mangle: {
        toplevel: true
      }
    });
    if (result.error) {
      console.error('Minification Error:', result.error);
    } else {
      console.log('Minified Code:\n', result.code);
      // Expected output will be a highly compressed version of the input JS
      // e.g., 'class Greeter{constructor(e){this.name=e}greet(){return"Hello, "+this.name+"!"}}const greeter=new Greeter("World");console.log(greeter.greet());'
    }
  } catch (e) {
    console.error('Unexpected Error:', e);
  }
}

runMinification();

view raw JSON →