Skip to content
Tutorials Center
My learning

Topics

Lesson 95 of 133 ยท Frameworks and Ecosystem

Building and Bundling

Learn when a Node.js project needs a build step - type stripping, tsc, esbuild, swc, tsup, how bundlers work, source maps, minification trade-offs and single executable apps.

A browser needs a build step because it downloads your code over a network, so smaller and fewer files load faster. Node.js reads files from disk, so the old answer was simple: no build step, just run node server.js. Today the picture is more nuanced. You may write TypeScript, ship a command-line tool as one file, run in a container where size matters, or hand a customer a program with no Node.js installed.

This lesson explains what each kind of build tool does, when you actually need one, and when you are better off without. It includes a small bundler written from scratch, so the magic disappears. Many examples here are read-only, because the editor has no npm packages and cannot run tsc or esbuild; where possible we run a stand-in or Node's own built-in tools.

Do you need a build step at all?

Start from the default: no build. Modern Node.js 22 to 24 runs ES modules, async/await, optional chaining, top-level await and fetch directly. If your code is plain JavaScript, node src/server.js in development and in production is perfectly good, easier to debug, and has fewer moving parts.

You add a build step when you need something Node cannot do alone:

Need Typical tool
Type check TypeScript tsc --noEmit
Turn TypeScript with non-erasable syntax into JavaScript tsc, esbuild, swc
Ship one file instead of a folder plus node_modules a bundler (esbuild, rollup, tsup)
Distribute a program to people without Node.js a single executable application
Compile-time constants, JSX, or a custom syntax esbuild, swc

Every build step costs you something: slower startup of your workflow, another configuration file, and a gap between the code you wrote and the code that runs. Pay that price only for a benefit you can name.

TypeScript: strip, check, emit

TypeScript adds types to JavaScript, but types do not exist at run time. There are really three different jobs, and people mix them up:

  1. Type checking: finding type errors. Only the TypeScript compiler (tsc) does this.
  2. Type stripping: removing the type annotations so the rest is valid JavaScript.
  3. Transpiling: rewriting newer syntax to older, or TypeScript-only syntax (enums, namespaces) into JavaScript.

Since Node.js 22.6 (flagged) and enabled by default in recent releases, Node can do job 2 by itself: it strips types from .ts files when you run them. It replaces the types with whitespace, so line and column numbers stay exactly the same and you need no source maps. The module node:module exposes the same function, so we can look at what it does.

Node.js What type stripping does to your code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The result has the same length and the same number of lines; the annotations became spaces. This function is marked experimental in Node 24, so you may see a warning on your machine. Because stripping only erases, it cannot handle syntax that generates code: enum, namespace with values, and constructor parameter properties are not erasable and fail by default. The lesson TypeScript with Node.js covers this, and the TypeScript tutorial covers the language itself.

What stripping does not do is check types. A common production setup is therefore:

Terminal
# Read-only: shows commands you run on your machine.
npx tsc --noEmit        # type check only, in CI and in your editor
node src/server.ts      # run directly, types are stripped at load time

Only if you need to publish compiled JavaScript (for example a library whose users do not run TypeScript), or you rely on non-erasable syntax, do you emit JavaScript with tsc or another tool.

Compilers and bundlers: what the names mean

These words are used loosely, so it helps to separate them.

  • A compiler/transpiler converts one file at a time from one language to another: tsc, swc (written in Rust), esbuild (written in Go), babel.
  • A bundler follows import statements from an entry point, collects every module it reaches, and writes them into one (or a few) output files: esbuild, rollup, webpack, rolldown.
  • A wrapper such as tsup (built on esbuild) gives library authors a one-line setup for the common case: bundle a TypeScript library to ESM and CommonJS and generate type declarations.

esbuild and swc are popular because they are very fast, often hundreds of times faster than older JavaScript-based tools. Note that esbuild does not type check; it just strips types and bundles. You still run tsc --noEmit for correctness.

A typical command-line build, again read-only:

Terminal
npm install --save-dev esbuild

npx esbuild src/server.ts \
  --bundle \
  --platform=node \
  --target=node24 \
  --format=esm \
  --sourcemap \
  --packages=external \
  --outfile=dist/server.mjs

Each flag matters for Node: --platform=node keeps built-ins like node:fs as they are; --target=node24 limits the output to features Node 24 supports (no needless rewriting); --packages=external leaves npm dependencies out of the bundle; --sourcemap writes a map so that stack traces point at your original source.

How a bundler works, in 40 lines

A bundler is not magic. It reads the entry file, finds its imports, reads those, and so on, building a dependency graph. Then it puts every module in one file inside a function wrapper (so they keep separate scopes), together with a tiny require function that runs each module once. Here is a drastically simplified version that works on in-memory "files" using CommonJS-style require.

Node.js A tiny bundler written from scratch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

That is the core idea behind every bundler: graph, wrap, run each module once. Real tools add much more: parsing ES import/export properly, resolving packages in node_modules, tree shaking (dropping exports nobody uses), code splitting, and source maps. They parse code into a syntax tree instead of using a regular expression, which is why you should never do this in a real project.

Source maps: keeping stack traces readable

When a tool rewrites or merges your code, an error at "line 1, column 48210 of server.mjs" is useless. A source map is a JSON file (or an inline comment) that maps positions in the generated file back to positions in your original files. Node.js reads source maps when you start it with --enable-source-maps (our editor already does), and stack traces then show your original file names and lines. The mapping uses a compact encoding, but Node can read it for you through SourceMap in node:module.

Node.js Looking up an original position in a source map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

(Lines are counted from 0 inside the API, so we add 1 for display.) You never write the mappings string yourself; the build tool does. What matters for you:

  • Ship source maps to your error tracker (Sentry and similar) or run production with --enable-source-maps, so traces are readable.
  • Source map support adds a cost when an Error is created (the stack is translated), so for hot paths that throw millions of errors, measure before enabling it in production.
  • Never serve source maps to the public for private server code unless you are comfortable showing the source. For servers this is rarely an issue because the code is not downloaded by users.

Minification: usually not for servers

Minification shortens names and removes whitespace to reduce bytes. It is essential for browser code that travels over a network. For a server process it brings almost nothing: the file is read from local disk once at startup, and V8 compiles it regardless of how short the names are. Meanwhile minified stack traces and logs become harder to read, and some code that depends on function.name or class.name (dependency-injection by name, error name fields, logging) can break when names are mangled.

A good default for servers is therefore: bundle if you want one file, but do not minify. Minify when size really matters: a CLI downloaded by many people, a serverless function with a package-size limit, or a single executable. If you do, keep names for classes and functions (--keep-names in esbuild).

When not to bundle a server

Bundling is not always a good idea for a Node.js server:

  • Native addons (.node files, such as bcrypt builds, sharp, database drivers) cannot be put inside a JavaScript bundle. They must stay as external files.
  • Dynamic requires and plugins (require(variable)) cannot be resolved at build time.
  • Files read relative to the package (fs.readFile(new URL('./schema.sql', import.meta.url))) break when the file layout changes, because the bundle moves code around.
  • Debugging and patching are harder: you cannot edit a dependency inside node_modules for a quick test.
  • Docker layer caching works better when dependencies (rarely changing) and your code (often changing) are separate layers; a single big bundle changes on every commit.

For these reasons many production servers simply run the plain source with a clean npm ci --omit=dev, using --packages=external if they build at all. Bundle libraries that you publish, CLIs, serverless functions and executables; think twice for long-running servers.

Libraries: dual packages and type declarations

If you publish a library, your consumers may use ESM or CommonJS and TypeScript. A build tool such as tsup produces both formats and .d.ts files in one command, and package.json describes them with exports (see Creating and Publishing Packages and ESM and CommonJS Interop):

JSON
{
  "name": "tiny-lib",
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js",
      "require": "./dist/index.cjs"
    }
  },
  "files": ["dist"],
  "scripts": {
    "build": "tsup src/index.ts --format esm,cjs --dts"
  }
}

Since Node 22 can require() an ES module, a library that only ships ESM is now usable from CommonJS too, which lets many new libraries skip the dual build entirely. Check the supported Node versions of your consumers before dropping CommonJS.

Single executable applications

Sometimes you want to give someone a program that runs without installing Node.js. Node.js has a built-in feature for this called single executable applications (SEA): it injects your script into a copy of the node binary. The result is one file that contains the whole runtime plus your code. The process is:

  1. Bundle your program into one CommonJS script (SEA's entry point is a single script, which is why a bundler is the first step).
  2. Write a small config file telling Node what to embed.
  3. Generate a blob, copy the node executable, and inject the blob with a tool called postject.
JSON
{
  "main": "dist/app.cjs",
  "output": "dist/app.blob",
  "disableExperimentalSEAWarning": true
}
Terminal
# Read-only: these commands run on your machine, not in our editor.
node --experimental-sea-config sea-config.json     # creates dist/app.blob
cp "$(command -v node)" dist/myapp                   # copy the node binary
npx postject dist/myapp NODE_SEA_BLOB dist/app.blob \
  --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2
./dist/myapp                                         # runs without Node installed

On Windows and macOS there are extra steps (removing and re-applying the code signature). The feature is still evolving, so check the current documentation for your Node version. The executable is large (it is the whole runtime, tens of megabytes) and one binary per operating system and CPU is needed. Your code can detect that it runs as an SEA with the node:sea module:

Node.js Asking whether we are a single executable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In our editor this prints false. Inside a real SEA it prints true, and sea.getAsset() can read files you embedded. Other options for distributing programs exist (Bun and Deno compile to executables, pkg-style tools), but SEA is the official Node way.

Build scripts and a sensible setup

Keep the build in package.json scripts so everyone and every CI machine runs the same commands (see package.json in Depth):

JSON
{
  "scripts": {
    "typecheck": "tsc --noEmit",
    "build": "esbuild src/server.ts --bundle --platform=node --target=node24 --format=esm --packages=external --sourcemap --outfile=dist/server.mjs",
    "start": "node --enable-source-maps dist/server.mjs",
    "dev": "node --watch src/server.ts"
  }
}

Good habits:

  • Output to dist/ (or build/), add it to .gitignore, and build in CI or in your Docker image, not by hand.
  • Pin the Node version (engines, .nvmrc, or the Docker base image) and build for that version with --target.
  • Run the type check and the tests in CI before the build.
  • Make builds reproducible: npm ci with a lock file, no network access at run time.
  • For development use node --watch instead of a build when you can. It restarts the process when files change and needs no configuration.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Node.js type stripping do?

    Stripping only erases erasable syntax and keeps line and column numbers. Type checking still needs tsc.
  2. 2. Which tool should you use to find type errors in a TypeScript project?

    Only the TypeScript compiler understands types well enough to check them. esbuild and swc just strip types.
  3. 3. What does a bundler do first, starting from the entry file?

    Bundlers walk the dependency graph from the entry point, then combine the modules into one or a few output files.
  4. 4. Why is minifying a long-running server usually not worth it?

    A server reads its code once at startup from local disk, so the saved bytes bring almost nothing, while mangled names hurt debugging and logs.
  5. 5. What is a single executable application (SEA) in Node.js?

    SEA injects a blob with your code into a copy of the Node.js binary, producing one executable that includes the runtime.

Summary

  • Default to no build: modern Node.js runs ES modules and recent syntax directly, and can strip TypeScript types itself.
  • Separate the jobs: type checking (tsc --noEmit), type stripping, transpiling and bundling.
  • A bundler follows imports from an entry file, wraps modules and combines them; tools like esbuild, swc, rollup and tsup do this far faster and more correctly than any hand-made version.
  • Use source maps (--enable-source-maps) whenever code is transformed so stack traces stay meaningful.
  • Do not minify servers by default; avoid bundling servers with native addons, dynamic requires or files read relative to the package.
  • Libraries need exports, ESM/CommonJS decisions and type declarations; executables can be built with Node's single executable application feature.
  • Keep build commands in package.json scripts and run them in CI.

Next: Deploying Node.js Applications