Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 39 ยท Bundler and Transpiler

Bun Build Basics

Learn what a bundler does and use bun build and the Bun.build API to bundle TypeScript for the browser, Bun or Node - entry points, outputs, targets, watch mode and reading build results.

Running code with bun run needs no build step. But when you ship code to a browser, to a server with few dependencies, or as a package for other people, a build step helps. A bundler reads your entry file, follows every import, and combines everything into a few optimised files. Bun has one built in, so bun build replaces tools like esbuild, Rollup or webpack for many projects, and it is fast because it shares the native parser with the runtime.

This lesson explains why you bundle, then runs your first builds with the command line and the Bun.build JavaScript API. The next lessons cover options, loaders, plugins and executables. Bun is not available on this page, so commands are read-only and a runnable stand-in shows the core algorithm.

Why bundle?

Browsers can load ES modules, but a real app has hundreds of files plus packages from node_modules. Loading them one by one means hundreds of requests, and browsers cannot resolve bare imports like import { z } from "zod" at all. Bundling fixes this:

  • Resolves every import, including node_modules packages and TypeScript or JSX files.
  • Combines modules into one file (or a few) to cut network requests.
  • Tree shakes: removes exports nobody uses.
  • Transforms TypeScript, JSX and newer syntax.
  • Minifies the output to reduce download size.
  • Hashes file names so browsers cache them safely.
flowchart LR
  A["index.tsx"] --> B["Bun bundler"]
  C["utils.ts"] --> B
  D["node_modules/zod"] --> B
  E["styles.css"] --> B
  B --> F["out/index.js"]
  B --> G["out/index.css"]

Many source files and packages go in; a handful of optimised files come out.

Your first build

Create two files:

TypeScript
// src/greet.ts
export function greet(name: string): string {
  return `Hello, ${name}!`;
}

export function unused(): string {
  return "nobody calls me";
}
TypeScript
// src/index.ts
import { greet } from "./greet";

console.log(greet("Bun"));

Bundle it into a folder:

Terminal
bun build ./src/index.ts --outdir ./dist

Bun creates dist/index.js. Open it and you will see the code of greet and the console.log call in one file, with the TypeScript types gone, and without unused, which was tree shaken. Run it with bun dist/index.js, which prints Hello, Bun!.

A few details:

  • --outdir writes one or more output files into a folder, named after each entry.
  • --outfile ./dist/app.js writes exactly one file (only valid with one entry point).
  • Without either, the bundled code prints to standard output, which is useful for quick inspection or piping.
  • You can give several entry points: bun build ./src/a.ts ./src/b.ts --outdir ./dist.

Choosing a target

The target says where the code will run:

--target Use for Notes
browser (default) Web pages Prefers browser package conditions; Node built-ins are not available.
bun Servers and scripts that run on Bun Keeps Bun-specific APIs; marks the file for Bun's fast loader.
node Code that runs on Node.js Targets Node-compatible output and conditions.
Terminal
bun build ./src/server.ts --outdir ./dist --target bun
bun build ./src/cli.ts --outdir ./dist --target node

Choosing wrongly gives errors such as "Could not resolve: node:fs" when bundling for the browser. That message means the code depends on something that does not exist where you said it will run.

The Bun.build API

Anything the command line does is available from code, which is how you write custom build scripts:

TypeScript
// build.ts
const result = await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  target: "bun",
});

if (!result.success) {
  for (const log of result.logs) {
    console.error(log.message);
  }
  process.exit(1);
}

for (const output of result.outputs) {
  console.log(output.path, output.kind, `${output.size} bytes`);
}

Run it with bun run build.ts. The returned object has:

Field Meaning
success true when the build had no errors
outputs An array of BuildArtifact objects
logs Messages: errors and warnings with file positions

Each BuildArtifact behaves like a Blob with extra fields: path, kind ("entry-point", "chunk", "asset", "sourcemap"), hash and loader. Because it is a Blob, you can read it (await output.text()) or return it from a server.

When you leave out outdir, nothing is written: the outputs stay in memory. That is perfect for tests and for dev servers that serve bundles straight from memory:

TypeScript
const result = await Bun.build({ entrypoints: ["./src/index.ts"] });
const code = await result.outputs[0].text();
console.log(code.length);

Depending on your Bun version, a failed build either returns success: false with logs or throws an AggregateError (the throw option controls it). Handling both with a try/catch plus the success check, as shown, keeps the script correct.

Watching and rebuilding

Terminal
bun build ./src/index.ts --outdir ./dist --watch

Bun rebuilds when any file in the import graph changes. For a front-end project with an HTML file, bun ./index.html starts a development server instead (see Loaders and HTML entry points).

A tiny bundler to see how it works

Real bundlers do much more, but the heart is simple: start at the entry, find imports, collect modules, and wrap them so they can require each other. This stand-in bundles three in-memory modules into one string and runs it:

Node.js Stand-in: a 30-line bundler (runs on Node 24)

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.

All three files ended up in one script, with a tiny module registry. Bun does the same thing with proper parsing, scope analysis, tree shaking and minification.

Reading the output

Look at the generated file at least once. You will notice:

  • Imports are gone: their code was inlined.
  • Types, comments and unused exports are gone (the last only when it is safe to remove them).
  • Names from different files that would clash are renamed.
  • With --minify, everything compresses into short names and no whitespace.

If the output is surprising, build without --minify and compare with the source. Understanding the bundle is the fastest way to debug production-only bugs.

A typical package.json for builds

JSON
{
  "scripts": {
    "build": "bun build ./src/index.ts --outdir ./dist --target bun",
    "build:web": "bun build ./src/main.tsx --outdir ./public/assets --minify",
    "dev:build": "bun run build --watch"
  }
}

Keep dist in .gitignore. The next lesson, Build Options, adds minification, source maps, code splitting and environment variables.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does tree shaking do?

    Tree shaking drops unused code from the output so bundles are smaller.
  2. 2. Which flag writes the bundle into a folder?

    --outdir writes each entry's output into the folder; --outfile writes one file.
  3. 3. What is the default build target?

    The default target is browser, so Node built-ins are not assumed to exist.
  4. 4. What happens when you call Bun.build without an outdir?

    Without outdir nothing is written; you read the results from result.outputs.

Summary

  • A bundler follows imports, combines modules, tree shakes, transforms and minifies code.
  • bun build ./entry.ts --outdir ./dist builds; --outfile writes one file; no flag prints to stdout.
  • --target browser|bun|node says where the output will run; browser is the default.
  • Bun.build({ entrypoints, outdir, target }) is the same bundler from code, returning success, outputs and logs.
  • Outputs are Blob-like BuildArtifact objects, and --watch rebuilds on change.

Next: Build Options: Minify, Sourcemaps, Splitting