TExcelTAD

esbuild from the Command Line

esbuild is a bundler and transpiler written in Go. It parses, links and prints in parallel with very little copying, and is typically 10–100× faster than JavaScript-based tools. That speed is why Vite uses it for dependency pre-bundling and why many libraries and CLIs build with it directly. This lesson covers the CLI; the next one covers the JavaScript API and plugins.

Transpile one file

Without --bundle, esbuild transforms a single file and prints it. TypeScript types are stripped, not checked:

bash · try it yourself
mkdir -p eb && cd eb
npm init -y > /dev/null && npm install -D esbuild@0.28.2 > /dev/null 2>&1
cat > price.ts <<'TS'
interface Item { name: string; cents: number }
export const total = (items: Item[]): number => items.reduce((sum, i) => sum + i.cents, 0);
const wrong: number = "not a number";   // a type error, but esbuild doesn't care
export const label = (i: Item) => `${i.name}: ${(i.cents / 100).toFixed(2)}`;
TS
npx esbuild price.ts
echo "--- exit code: $?"
export const total = (items) => items.reduce((sum, i) => sum + i.cents, 0);
const wrong = "not a number";
export const label = (i) => `${i.name}: ${(i.cents / 100).toFixed(2)}`;
--- exit code: 0

The type error went straight through. That's by design: esbuild treats each file in isolation and never builds a type graph. Run tsc --noEmit separately (in CI, in your editor) for type checking; esbuild is only the compiler.

Bundle for different targets

--format decides the module wrapper, --platform the defaults for resolution and built-ins, --target which syntax may appear in the output:

Option Values
--format iife (default for browser bundles: one self-running script), esm, cjs
--platform browser (default), node (Node built-ins external, cjs default), neutral
--target es2015 … esnext, node20, chrome120, safari16, combinable with commas
bash · try it yourself
mkdir -p eb/src && cd eb
npm init -y > /dev/null && npm install -D esbuild@0.28.2 > /dev/null 2>&1
cat > src/config.js <<'JS'
export const port = (cfg) => cfg?.server?.port ?? 8080;
JS
echo "--- esm, esnext"
npx esbuild src/config.js --bundle --format=esm --log-level=warning
echo "--- cjs, es2019 (no ?. or ??)"
npx esbuild src/config.js --bundle --format=cjs --target=es2019 --log-level=warning | tail -4
--- esm, esnext
// src/config.js
var port = (cfg) => cfg?.server?.port ?? 8080;
export {
  port
};
--- cjs, es2019 (no ?. or ??)
var port = (cfg) => {
  var _a, _b;
  return (_b = (_a = cfg == null ? void 0 : cfg.server) == null ? void 0 : _a.port) != null ? _b : 8080;
};

With --target=es2019, esbuild lowered optional chaining and ?? to older syntax. It only transforms syntax: it doesn't add polyfills for missing APIs (like Array.prototype.at); that's a separate decision (a polyfill import, or core-js).

A production build for Node

bash · try it yourself
mkdir -p cli/src && cd cli
npm init -y > /dev/null && npm pkg set type=module
npm install ms@2.1.3 chalk@6.0.1 > /dev/null && npm install -D esbuild@0.28.2 > /dev/null 2>&1
cat > src/cli.js <<'JS'
import ms from 'ms';
import chalk from 'chalk';
import { readFileSync } from 'node:fs';
const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url)));
if (process.env.NODE_ENV !== 'production') console.log('debug build');
console.log(chalk.bold(`timer v${__VERSION__ ?? version}`), ms(Number(process.argv[2] ?? 0)));
JS
npx esbuild src/cli.js --bundle --platform=node --format=esm --target=node20 \
  --define:process.env.NODE_ENV='"production"' --define:__VERSION__='"1.0.0"' \
  --external:chalk --minify --sourcemap --outfile=dist/cli.js
grep -c 'debug build' dist/cli.js
grep -o 'from"[a-z:]*"' dist/cli.js
node dist/cli.js 90000

  dist/cli.js      2.1kb
  dist/cli.js.map  5.8kb

⚡ Done in 4ms
0
from"chalk"
from"node:fs"
timer v1.0.0 2m

What the flags did:

  • --platform=node left node:fs as an import instead of trying to bundle it.
  • --define replaced the expressions at build time; with NODE_ENV known to be "production", the minifier removed the dead if branch entirely (grep -c finds no "debug build").
  • --external:chalk kept import … from "chalk" in the output, so chalk is loaded from node_modules at runtime (and must stay in dependencies); ms was inlined.
  • --sourcemap wrote dist/cli.js.map, so stack traces point at src/cli.js.

Loaders

esbuild picks a loader per file extension: js, jsx, ts, tsx, json, css, text, base64, dataurl, file, binary, copy, empty. Change it with --loader:.ext=name:

bash · try it yourself
mkdir -p ld && cd ld
npm init -y > /dev/null && npm install -D esbuild@0.28.2 > /dev/null 2>&1
echo 'Hello from a text file' > greeting.txt
echo '{ "retries": 3, "unused": "dropped?" }' > settings.json
cat > main.js <<'JS'
import greeting from './greeting.txt';
import { retries } from './settings.json';
console.log(greeting.trim(), '| retries =', retries);
JS
npx esbuild main.js --bundle --loader:.txt=text --format=esm --outfile=out.mjs --log-level=warning
node out.mjs
grep -c 'dropped' out.mjs
Hello from a text file | retries = 3
0

The text file became a string and the JSON file an object. grep -c found no trace of "dropped?": with a named import, the JSON loader even tree-shakes unused top-level keys.

Watch and serve

--watch rebuilds on every change, and --serve=8000 (with --servedir) runs a development server that rebuilds on each request. Both are for development only: they don't do hot module replacement, which is why application developers usually reach for Vite instead.

bash
npx esbuild src/app.jsx --bundle --outdir=www/js --watch
npx esbuild src/app.jsx --bundle --outdir=www/js --servedir=www --serve=8000

Test yourself

What does esbuild do with a TypeScript type error?

  1. Fails the build
  2. Strips the types and builds anyway; type checking is tsc's job
  3. Prints a warning and skips the file
  4. Converts it to any

What does --external:chalk do in a bundle?

  1. Downloads chalk from a CDN
  2. Leaves the import of chalk in the output instead of inlining it
  3. Removes chalk calls
  4. Bundles chalk into a separate chunk

With --target=es2019, what happens to a?.b ?? c?

  1. Build error
  2. It is rewritten into equivalent ES2019 syntax
  3. A polyfill is added
  4. It is left unchanged