ZetCode

Gulp esbuild

last modified November 15, 2026

In this article we bundle JavaScript modules with Gulp 5 and esbuild. We use the gulp-esbuild plugin, call esbuild directly from a task, split shared code into chunks and rebuild only what changed in watch mode.

Bundling with esbuild

Modern JavaScript is written as ES modules in many small files. A bundler follows the import statements, removes the code that is never used (tree shaking) and joins the modules into a few files for the browser. esbuild is a bundler written in Go; it is much faster than the older JavaScript bundlers, and it also minifies code and creates source maps. The Gulp concat tutorial joins files by pasting them one after another; a bundler understands the dependencies between modules instead.

There are two ways to use esbuild in Gulp. The gulp-esbuild plugin fits into a src().pipe() chain. The other way is to call the build function of the esbuild package from an async task, which needs no plugin. We try both.

Installing the project

We create a project and install Gulp, esbuild and the plugin. The npm init -y command of recent npm versions writes "type": "commonjs" to package.json; we change it to module because the sources are ES modules (the next sections explain why this matters).

$ mkdir gulp-esbuild
$ cd gulp-esbuild
$ npm init -y
$ npm pkg set type=module
$ npm i -D gulp esbuild gulp-esbuild
$ mkdir -p src/js

The example project

The sources are four small modules in src/js. The math.js module exports a function that nobody imports; a bundler should leave it out.

src/js/math.js
export function add(a, b) {
    return a + b;
}

export function square(x) {
    return x * x;
}

export function unused() {
    return 'never imported';
}
src/js/greet.js
export default function greet(name) {
    return `Hello, ${name}!`;
}

The main.js module imports both modules and uses them; admin.js is a second entry point that shares the modules with main.js.

src/js/main.js
import greet from './greet.js';
import { add, square } from './math.js';

console.log(greet('Gulp'));
console.log('2 + 3 =', add(2, 3));
console.log('4 squared =', square(4));
src/js/admin.js
import { square } from './math.js';
import greet from './greet.js';

console.log(greet('admin'), square(9));

The gulpfile

The gulpfile has five tasks. The first four build the bundle in different ways and the last one watches the sources. We look at them in the following sections.

gulpfile.mjs
import { src, dest, watch } from 'gulp';
import { gulpEsbuild } from 'gulp-esbuild';
import { build as esbuild, context } from 'esbuild';

export function plugin() {

    return src('src/js/main.js')
        .pipe(gulpEsbuild({
            entryPoints: ['src/js/main.js'],
            outfile: 'main.bundle.js',
            bundle: true,
            minify: true,
            sourcemap: true,
            target: 'es2020'
        }))
        .pipe(dest('dist/plugin'));
}

export async function direct() {

    await esbuild({
        entryPoints: ['src/js/main.js'],
        outfile: 'dist/direct/main.bundle.js',
        bundle: true,
        minify: true,
        sourcemap: true,
        target: 'es2020',
        logLevel: 'info'
    });
}

export async function split() {

    await esbuild({
        entryPoints: ['src/js/main.js', 'src/js/admin.js'],
        outdir: 'dist/split',
        bundle: true,
        splitting: true,
        format: 'esm',
        minify: true,
        logLevel: 'info'
    });
}

export async function readable() {

    await esbuild({
        entryPoints: ['src/js/main.js'],
        outfile: 'dist/readable/main.js',
        bundle: true,
        logLevel: 'info'
    });
}

export async function develop() {

    const ctx = await context({
        entryPoints: ['src/js/main.js'],
        outfile: 'dist/develop/main.bundle.js',
        bundle: true,
        sourcemap: 'inline',
        logLevel: 'info'
    });

    await ctx.rebuild();

    watch('src/js/**/*.js', async function rebuild() {

        await ctx.rebuild().catch(() => {});
    });
}

The gulpfile is an ES module, as in the ESM gulpfile tutorial.

Calling esbuild directly

The direct task awaits the build function. The entryPoints option lists the modules where the bundling starts, bundle: true follows the imports, and outfile is the result. The minify option shortens the code and sourcemap writes a separate map file. The target option tells esbuild which JavaScript version to emit, and logLevel: 'info' prints a summary of the written files.

export async function direct() {

    await esbuild({
        entryPoints: ['src/js/main.js'],
        outfile: 'dist/direct/main.bundle.js',
        bundle: true,
        minify: true,
        sourcemap: true,
        target: 'es2020',
        logLevel: 'info'
    });
}

The task returns the promise of the build, so Gulp knows when it has finished. The output is one line, 224 bytes; the unused unused function and the unused exports are gone, and the file runs on its own.

$ npx gulp direct
[13:43:43] Using gulpfile ~/Documents/prog/js/gulp-esbuild/gulpfile.mjs
[13:43:43] Starting 'direct'...
[13:43:43] Finished 'direct' after 11 ms

  dist/direct/main.bundle.js      224b 
  dist/direct/main.bundle.js.map  925b 

⚡ Done in 2ms
$ cat dist/direct/main.bundle.js
(()=>{function o(e){return`Hello, ${e}!`}function r(e,n){return e+n}function t(e){return e*e}console.log(o("Gulp"));console.log("2 + 3 =",r(2,3));console.log("4 squared =",t(4));})();
//# sourceMappingURL=main.bundle.js.map
$ node dist/direct/main.bundle.js
Hello, Gulp!
2 + 3 = 5
4 squared = 16

Readable output

Without minify the bundle keeps names and formatting, which helps to see what esbuild does. The readable task builds the same entry point and writes the file with the modules in the order of their dependencies, each marked by a comment with its path.

await esbuild({
    entryPoints: ['src/js/main.js'],
    outfile: 'dist/readable/main.js',
    bundle: true,
    logLevel: 'info'
});

The result is wrapped in an immediately invoked function so that nothing leaks into the global scope. The unused function from math.js was removed by tree shaking.

$ npx gulp readable --silent

  dist/readable/main.js  335b 

⚡ Done in 3ms
$ cat dist/readable/main.js
(() => {
  // src/js/greet.js
  function greet(name) {
    return `Hello, ${name}!`;
  }

  // src/js/math.js
  function add(a, b) {
    return a + b;
  }
  function square(x) {
    return x * x;
  }

  // src/js/main.js
  console.log(greet("Gulp"));
  console.log("2 + 3 =", add(2, 3));
  console.log("4 squared =", square(4));
})();

The type field of package.json

Tree shaking works only if esbuild knows that the files are ES modules. Newer esbuild versions follow the type field of the nearest package.json for .js files. With the default "type": "commonjs" that npm init creates, the same sources are treated as CommonJS: the bundle is full of __esm and __commonJS helper functions, nothing is shaken out, and the output is twice as big. Either set "type": "module" or name the files .mjs. We switch the field back for a moment and rebuild to see the difference.

$ npm pkg set type=commonjs
$ npx gulp direct --silent

  dist/direct/main.bundle.js      466b 
  dist/direct/main.bundle.js.map  1.1kb

⚡ Done in 2ms
$ wc -c dist/direct/main.bundle.js
466 dist/direct/main.bundle.js
$ npm pkg set type=module
$ npx gulp direct --silent

  dist/direct/main.bundle.js      224b 
  dist/direct/main.bundle.js.map  925b 

⚡ Done in 2ms
$ wc -c dist/direct/main.bundle.js
224 dist/direct/main.bundle.js

The gulp-esbuild plugin

The plugin task uses gulp-esbuild in a pipeline. The plugin takes the same options as esbuild, and the bundle it produces is a file in the stream that dest writes. The entryPoints option is required even though src already names the file.

return src('src/js/main.js')
    .pipe(gulpEsbuild({
        entryPoints: ['src/js/main.js'],
        outfile: 'main.bundle.js',
        bundle: true,
        minify: true,
        sourcemap: true,
        target: 'es2020'
    }))
    .pipe(dest('dist/plugin'));

Here outfile is only a name, and dest decides the directory. The bundle and the map are written, and the bundle is identical to the one from the direct build. Without entryPoints the task never finishes: Gulp prints "did not complete" and writes nothing.

$ npx gulp plugin --silent
$ ls dist/plugin
main.bundle.js
main.bundle.js.map
$ cmp dist/plugin/main.bundle.js dist/direct/main.bundle.js

Splitting shared code

When two pages use the same modules, bundling them separately duplicates the shared code. With the splitting option esbuild moves the shared modules into a chunk that both entry points import. Splitting needs the ES module output format, so we set format: 'esm' and use outdir instead of outfile, because there are several output files.

await esbuild({
    entryPoints: ['src/js/main.js', 'src/js/admin.js'],
    outdir: 'dist/split',
    bundle: true,
    splitting: true,
    format: 'esm',
    minify: true,
    logLevel: 'info'
});

The output has three files. The chunk contains greet and square, and also add, which only main.js uses; esbuild put the whole math.js module and the greet.js module there. Both entries import the chunk. The files are ES modules, so a page loads them with <script type="module" src="main.js"> and the browser fetches the chunk once.

$ npx gulp split
[13:43:45] Using gulpfile ~/Documents/prog/js/gulp-esbuild/gulpfile.mjs
[13:43:45] Starting 'split'...
[13:43:45] Finished 'split' after 10 ms

  dist/split/main.js            140b 
  dist/split/chunk-KKFADNCD.js  117b 
  dist/split/admin.js            77b 

⚡ Done in 2ms
$ cat dist/split/main.js
import{a as o,b as e,c as l}from"./chunk-KKFADNCD.js";console.log(o("Gulp"));console.log("2 + 3 =",e(2,3));console.log("4 squared =",l(4));
$ cat dist/split/admin.js
import{a as o,c as r}from"./chunk-KKFADNCD.js";console.log(o("admin"),r(9));

Errors

If a source file has a syntax error, the two approaches behave differently. We append an invalid line to main.js. The direct task prints the error of esbuild, with the position, and fails with a non-zero exit code. The plugin task does not print the error at all: Gulp only says that the task did not complete, as the error of the plugin is swallowed in the stream (the Gulp error handling tutorial describes this problem). This is a good reason to prefer the direct call.

$ npx gulp direct
[13:43:45] Using gulpfile ~/Documents/prog/js/gulp-esbuild/gulpfile.mjs
[13:43:45] Starting 'direct'...
✘ [ERROR] Expected identifier but found "="

    src/js/main.js:7:6:
      7 │ const = ;
        ╵       ^

1 error
[13:43:45] 'direct' errored after 9.85 ms
[13:43:45] Error: Build failed with 1 error:
src/js/main.js:7:6: ERROR: Expected identifier but found "="
$ echo $?
1
$ npx gulp plugin
[13:43:46] Using gulpfile ~/Documents/prog/js/gulp-esbuild/gulpfile.mjs
[13:43:46] Starting 'plugin'...
[13:43:46] The following tasks did not complete: plugin
Did you forget to signal async completion?
$ echo $?
1

Rebuilding in watch mode

A fresh bundle for every change wastes time. The context function of esbuild creates a build context whose rebuild method reuses the work of the previous build, so only the changed files are parsed again. The develop task builds once, and the function passed to watch rebuilds when any module changes. The .catch() keeps the watcher alive after a syntax error, which esbuild has already printed. We also write the source map inline, which is common during development.

const ctx = await context({
    entryPoints: ['src/js/main.js'],
    outfile: 'dist/develop/main.bundle.js',
    bundle: true,
    sourcemap: 'inline',
    logLevel: 'info'
});

await ctx.rebuild();

watch('src/js/**/*.js', async function rebuild() {

    await ctx.rebuild().catch(() => {});
});

We start the task and in another terminal append a line to greet.js, then break the file and fix it. Every save triggers a rebuild task; the second one reports the syntax error, and the third one succeeds again. The task is stopped with Ctrl+C. The Gulp watch tutorial explains the watch function.

$ npx gulp develop
[13:43:46] Using gulpfile ~/Documents/prog/js/gulp-esbuild/gulpfile.mjs
[13:43:46] Starting 'develop'...
[13:43:46] Finished 'develop' after 13 ms
[13:43:49] Starting 'rebuild'...
[13:43:49] Finished 'rebuild' after 7.81 ms
[13:43:51] Starting 'rebuild'...
✘ [ERROR] Expected identifier but found "="

    src/js/greet.js:5:6:
      5 │ const = ;
        ╵       ^

1 error
[13:43:51] Finished 'rebuild' after 4.99 ms
[13:43:52] Starting 'rebuild'...
[13:43:52] Finished 'rebuild' after 4.89 ms

Source

esbuild API, gulp-esbuild on npm, esbuild splitting

In this article we have bundled JavaScript with Gulp 5 and esbuild: we called esbuild directly and through gulp-esbuild, minified and split the output, and rebuilt incrementally in watch mode. See also the Gulp Terser and Gulp source maps tutorials.

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.