TExcelTAD

esbuild's JS API, Plugins & Limits

The CLI covers simple builds. Real projects want a build script: several outputs, values computed at build time, a plugin or two, and a check of the result. esbuild exposes the same engine through a JavaScript API (build, context, transform), and its plugin system hooks into resolving and loading modules.

A build script

bash · try it yourself
mkdir -p api/src && cd api
npm init -y > /dev/null && npm pkg set type=module
npm install ms@2.1.3 > /dev/null && npm install -D esbuild@0.28.2 > /dev/null 2>&1
cat > src/index.js <<'JS'
import ms from 'ms';
export const uptime = (n) => `up ${ms(n)}`;
JS
cat > build.mjs <<'JS'
import * as esbuild from 'esbuild';

const common = { entryPoints: ['src/index.js'], bundle: true, platform: 'node', target: 'node20', logLevel: 'warning' };

// Two formats from one source.
await esbuild.build({ ...common, format: 'esm', outfile: 'dist/index.js' });
await esbuild.build({ ...common, format: 'cjs', outfile: 'dist/index.cjs' });

// In memory: don't write, inspect the result instead.
const result = await esbuild.build({ ...common, format: 'esm', minify: true, outfile: 'dist/index.min.js', write: false, metafile: true });
for (const file of result.outputFiles) console.log('in memory:', file.path.replace(process.cwd() + '/', ''), file.contents.length, 'bytes');
console.log('inputs:', Object.keys(result.metafile.inputs).join(', '));

// transform(): one string in, one string out (what Vite and test runners use per file).
const { code } = await esbuild.transform('let x: number = 1 satisfies number', { loader: 'ts' });
console.log('transform:', code.trim());
JS
node build.mjs
ls dist
node -e 'console.log(require("./dist/index.cjs").uptime(3600000))'
node --input-type=module -e 'import { uptime } from "./dist/index.js"; console.log(uptime(60000))'
in memory: dist/index.min.js 1967 bytes
inputs: node_modules/ms/index.js, src/index.js
transform: let x = 1;
index.cjs
index.js
up 1h
up 1m

ls dist shows only the two written builds: dist/index.min.js exists only in memory. With write: false you get the output files as bytes, which build scripts use for checks (size budgets, forbidden strings) or to hand the code to something else, such as a test runner.

Plugins: onResolve and onLoad

A plugin is an object with a name and a setup(build) function that registers callbacks:

  • build.onResolve({ filter, namespace }, cb): decide where an import path points (or mark it external).
  • build.onLoad({ filter, namespace }, cb): provide the contents for a path (and its loader).
  • build.onStart, build.onEnd: run around each build, e.g. to print a summary.

filter is a Go regular expression that esbuild evaluates before calling into JavaScript, so a plugin only pays for the paths it cares about. Two classic plugins: a virtual module with build-time data, and an import guard.

bash · try it yourself
mkdir -p plug/src && cd plug
npm init -y > /dev/null && npm pkg set type=module
npm install -D esbuild@0.28.2 > /dev/null 2>&1
cat > src/index.js <<'JS'
import { builtAt, commit } from 'build-info';
console.log(`built ${builtAt} from ${commit}`);
JS
cat > src/bad.js <<'JS'
import fs from 'node:fs';
console.log(fs.existsSync('.'));
JS
cat > build.mjs <<'JS'
import * as esbuild from 'esbuild';

const buildInfo = {
  name: 'build-info',
  setup(build) {
    build.onResolve({ filter: /^build-info$/ }, (args) => ({ path: args.path, namespace: 'build-info' }));
    build.onLoad({ filter: /.*/, namespace: 'build-info' }, () => ({
      contents: JSON.stringify({ builtAt: new Date(Number(process.env.SOURCE_DATE_EPOCH) * 1000).toISOString(), commit: 'abc1234' }),
      loader: 'json',
    }));
  },
};

const noNodeBuiltins = {
  name: 'no-node-builtins',
  setup(build) {
    build.onResolve({ filter: /^node:/ }, (args) => ({
      errors: [{ text: `"${args.path}" can't be used in browser code (imported by ${args.importer})` }],
    }));
  },
};

const options = { bundle: true, format: 'esm', write: false, logLevel: 'silent', plugins: [buildInfo, noNodeBuiltins] };
const ok = await esbuild.build({ ...options, entryPoints: ['src/index.js'] });
console.log(ok.outputFiles[0].text);
try {
  await esbuild.build({ ...options, entryPoints: ['src/bad.js'] });
} catch (e) {
  for (const err of e.errors) console.log(`error [${err.pluginName}]: ${err.text}`);
}
JS
node build.mjs
// build-info:build-info
var builtAt = "2026-01-01T00:00:00.000Z";
var commit = "abc1234";

// src/index.js
console.log(`built ${builtAt} from ${commit}`);

error [no-node-builtins]: "node:fs" can't be used in browser code (imported by /home/learner/plug/src/bad.js)

The virtual build-info module never existed on disk. The import guard turned a mistake (Node APIs in browser code) into a build error naming the plugin, the import and the importer. The build date comes from SOURCE_DATE_EPOCH, not the clock, so the output is reproducible.

Incremental rebuilds: context()

esbuild.context(options) keeps the parsed graph in memory between builds. ctx.rebuild() only redoes work for changed files; ctx.watch() and ctx.serve() build on the same object.

bash · try it yourself
mkdir -p inc/src && cd inc
npm init -y > /dev/null && npm pkg set type=module
npm install -D esbuild@0.28.2 > /dev/null 2>&1
echo 'export const msg = "v1";' > src/msg.js
echo 'import { msg } from "./msg.js"; console.log(msg);' > src/index.js
cat > dev.mjs <<'JS'
import * as esbuild from 'esbuild';
import { writeFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';

const ctx = await esbuild.context({ entryPoints: ['src/index.js'], bundle: true, outfile: 'dist/out.js', logLevel: 'silent' });
await ctx.rebuild();
console.log('first build  ->', execFileSync('node', ['dist/out.js']).toString().trim());
writeFileSync('src/msg.js', 'export const msg = "v2";');
await ctx.rebuild();
console.log('after change ->', execFileSync('node', ['dist/out.js']).toString().trim());
await ctx.dispose();
JS
node dev.mjs
first build  -> v1
after change -> v2

Limits worth knowing

esbuild is deliberately narrow. Before choosing it as your only build tool, check these:

Limit What to do
no type checking run tsc --noEmit alongside
no .d.ts generation tsc --emitDeclarationOnly (see TypeScript libraries)
no hot module replacement use Vite for app development
syntax lowering stops at ES2015 (es5 targets fail for many features) use another compiler (SWC, Babel) if you must ship ES5
no API polyfills add core-js or targeted imports yourself
fewer output-shaping hooks than Rollup (no chunk-level renderChunk, manualChunks) Rollup for libraries that need precise output
code splitting only with format: 'esm' fine for modern browsers and Node
decorators: only the TC39 standard ones and TypeScript's experimentalDecorators, no emitDecoratorMetadata frameworks relying on metadata (NestJS, TypeORM) need tsc or SWC

None of these are bugs. They're why the ecosystem uses esbuild as a fast component (Vite's dev transforms, tsx, Vitest) as often as a complete build tool.

Test yourself

What does write: false give you in esbuild.build()?

  1. A dry run with no output
  2. The output files in memory (result.outputFiles) instead of on disk
  3. Faster minification
  4. Only the metafile

Why should an esbuild plugin's filter be as specific as possible?

  1. Go regexes are case-sensitive
  2. esbuild checks the filter natively before calling JavaScript, so narrow filters avoid slow callbacks
  3. Filters are required by the TypeScript types
  4. Broad filters break caching

Which of these can esbuild NOT do on its own?

  1. Bundle TypeScript
  2. Minify
  3. Generate .d.ts declaration files
  4. Write source maps