ZetCode

Gulp Terser

last modified November 15, 2026

In this article we configure Terser in Gulp 5 with the gulp-terser plugin. We compare the default settings with a switched-off mangler, remove console calls and debugger statements, enable top-level mangling, and keep function and class names.

Terser and gulp-terser

Terser is a JavaScript minifier. It works in three steps. The parser reads the source, the compressor rewrites the code into a smaller equivalent (it removes dead branches, inlines constants and joins statements), and the mangler shortens the names of local variables. The output stage then prints the code with the chosen format. The gulp-terser plugin takes Terser's options as an object, so each of the steps can be tuned.

Installing the project

We create a project and install Gulp and the plugin.

$ mkdir gulp-terser
$ cd gulp-terser
$ npm init -y
$ npm i -D gulp gulp-terser
$ mkdir src

The example project

The script calculates the price of an order. It contains everything a minifier can act on: comments, a license comment, a constant that disables a debug branch, a debugger statement, a function that is never called, a class, and console calls.

src/app.js
/*! app v1.0 | MIT License */

// Calculates the total price of an order.
const TAX_RATE = 0.2;
const DEBUG = false;

function calculateTotal(items) {

    let total = 0;

    for (const item of items) {
        total += item.price * item.quantity;
    }

    if (DEBUG) {
        console.log('debug: total is', total);
    }

    debugger;

    return total * (1 + TAX_RATE);
}

function unusedHelper() {
    return 'never called';
}

class Order {

    constructor(items) {
        this.items = items;
    }

    getTotal() {
        console.log('computing total');
        return calculateTotal(this.items);
    }
}

const order = new Order([{ price: 10, quantity: 2 }, { price: 5, quantity: 4 }]);
console.log(order.getTotal());

The file has 733 bytes. The order costs 10 × 2 + 5 × 4 = 40, plus 20 % tax, so the script prints 48. The gulpfile has a task for each Terser configuration.

gulpfile.mjs
import { src, dest } from 'gulp';
import terser from 'gulp-terser';

export function basic() {

    return src('src/app.js')
        .pipe(terser())
        .pipe(dest('dist/basic'));
}

export function noMangle() {

    return src('src/app.js')
        .pipe(terser({ mangle: false, compress: false, format: { beautify: true } }))
        .pipe(dest('dist/nomangle'));
}

export function production() {

    return src('src/app.js')
        .pipe(terser({
            compress: { drop_console: true, drop_debugger: true, passes: 2 },
            format: { comments: false }
        }))
        .pipe(dest('dist/production'));
}

export function toplevel() {

    return src('src/app.js')
        .pipe(terser({ toplevel: true, compress: { passes: 2 }, format: { comments: false } }))
        .pipe(dest('dist/toplevel'));
}

export function keepNames() {

    return src('src/app.js')
        .pipe(terser({ keep_classnames: true, keep_fnames: true, toplevel: true }))
        .pipe(dest('dist/keepnames'));
}

Each task reads src/app.js, minifies it with different options, and writes the result into its own directory.

The default options

The basic task calls terser() without options. The output keeps the /*! license comment, and drops the other comments and whitespace. The compressor replaced DEBUG with !1 and removed the if (DEBUG) branch and the debugger statement; it inlined the tax rate as 1.2. The names inside the functions are shortened (items became t), but the top-level names calculateTotal, unusedHelper and Order remain, because other scripts on the page could use them.

$ npx gulp basic --silent
$ cat dist/basic/app.js
/*! app v1.0 | MIT License */
const TAX_RATE=.2,DEBUG=!1;function calculateTotal(t){let e=0;for(const o of t)e+=o.price*o.quantity;return 1.2*e}function unusedHelper(){return"never called"}class Order{constructor(t){this.items=t}getTotal(){return console.log("computing total"),calculateTotal(this.items)}}const order=new Order([{price:10,quantity:2},{price:5,quantity:4}]);console.log(order.getTotal());
$ node dist/basic/app.js
computing total
48

Switching off the mangler and compressor

To see what Terser does, we switch off the compressor and mangler, and ask for readable output with format.beautify. The code is then only reformatted: the comments are removed, and the object literals are laid out by the printer. The result is useful for debugging a problem that may be caused by minification. If the unminified output works and the minified does not, we can turn the steps on one at a time.

terser({ mangle: false, compress: false, format: { beautify: true } })

The file is almost as big as the source.

$ npx gulp noMangle --silent
$ head -12 dist/nomangle/app.js
/*! app v1.0 | MIT License */
const TAX_RATE = .2;

const DEBUG = false;

function calculateTotal(items) {
    let total = 0;
    for (const item of items) {
        total += item.price * item.quantity;
    }
    if (DEBUG) {
        console.log("debug: total is", total);
$ wc -c src/app.js dist/nomangle/app.js
 733 src/app.js
 700 dist/nomangle/app.js
1433 total

Dropping console calls and comments

For production we often remove debugging code. The compress option drop_console removes all calls of console methods and drop_debugger removes debugger statements (the latter is on by default). With passes: 2 Terser runs the compressor twice, which sometimes finds a further saving. The format.comments option controls which comments survive; false removes them all, including the license comment.

terser({
    compress: { drop_console: true, drop_debugger: true, passes: 2 },
    format: { comments: false }
})

The output has no comment. Note that drop_console also removed the last statement of the script, which prints the result with console.log. The option does not care why the call is there, so it must not be used for scripts whose output goes to the console. If we remove the license comment, we must keep the license text in another place.

$ npx gulp production --silent
$ cat dist/production/app.js
const TAX_RATE=.2,DEBUG=!1;function calculateTotal(t){let e=0;for(const r of t)e+=r.price*r.quantity;return 1.2*e}function unusedHelper(){return"never called"}class Order{constructor(t){this.items=t}getTotal(){return calculateTotal(this.items)}}const order=new Order([{price:10,quantity:2},{price:5,quantity:4}]);
$ node dist/production/app.js
$ wc -c dist/production/app.js
313 dist/production/app.js

Top-level mangling

By default Terser leaves the top-level names alone, because in a classic script they are global variables that other scripts may use. When the file is a module or a self-contained bundle, we can allow Terser to touch them with toplevel: true. The mangler then renames order, the compressor removes the unused function unusedHelper, and inlines calculateTotal and the class into the single place where they are used.

terser({ toplevel: true, compress: { passes: 2 }, format: { comments: false } })

The script is now 254 bytes, about a third of the source, and prints the same number.

$ npx gulp toplevel --silent
$ cat dist/toplevel/app.js
const t=new class{constructor(t){this.items=t}getTotal(){return console.log("computing total"),function(t){let o=0;for(const n of t)o+=n.price*n.quantity;return 1.2*o}(this.items)}}([{price:10,quantity:2},{price:5,quantity:4}]);console.log(t.getTotal());
$ node dist/toplevel/app.js
computing total
48
$ wc -c dist/toplevel/app.js
254 dist/toplevel/app.js

Keeping function and class names

The mangler breaks code that depends on the name property of a function or a class, such as logging, dependency injection by name, or error messages. The keep_fnames and keep_classnames options exclude them from mangling. With these options, Order and calculateTotal keep their names, while the local variables are still shortened.

terser({ keep_classnames: true, keep_fnames: true, toplevel: true })

The file is a little larger than the previous one, because of the names, and the license comment is back, since this task does not touch format.comments.

$ npx gulp keepNames --silent
$ cat dist/keepnames/app.js
/*! app v1.0 | MIT License */
const t=new class Order{constructor(t){this.items=t}getTotal(){return console.log("computing total"),function calculateTotal(t){let o=0;for(const e of t)o+=e.price*e.quantity;return 1.2*o}(this.items)}}([{price:10,quantity:2},{price:5,quantity:4}]);console.log(t.getTotal());
$ node dist/keepnames/app.js
computing total
48
$ wc -c dist/keepnames/app.js
305 dist/keepnames/app.js

Syntax errors

A syntax error in the source does not make the task fail when the plugin is used in a pipe chain. How to make such errors visible is described in the Gulp error handling tutorial, and source maps for the minified file in the Gulp source maps tutorial.

Source

Terser API reference, Terser options, gulp-terser on npm

In this article we have configured Terser in Gulp 5: we compared the default options with the disabled mangler, removed console calls and comments, enabled top-level mangling, and kept function and class names. See also the Gulp concat tutorial.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Gulp tutorials.