Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 39 ยท Bundler and Transpiler

Build Options: Minify, Sourcemaps, Splitting

Master the main bun build options - minify, sourcemap, splitting, external, define and env, naming with hashes, public paths, drop, banner and format - with CLI and Bun.build examples.

Once a basic build works, the options decide how good the output is: how small it is, whether you can debug it, how it is split for fast page loads, which packages stay out of the bundle, and which constants are baked in. This lesson goes through the options you will use in real projects. Each is shown for both the command line and Bun.build, since they map one-to-one.

All Bun commands are read-only blocks; runnable Node stand-ins illustrate a few of the ideas.

Minification

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

--minify turns on three transformations. You can pick them individually:

Flag What it does
--minify-whitespace Removes spaces, newlines and comments.
--minify-syntax Rewrites code to shorter equivalents (if to ternary, constant folding).
--minify-identifiers Renames local variables to one or two letters.
TypeScript
await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  minify: true, // or { whitespace: true, syntax: true, identifiers: false }
});

Minify for production, not during development: it makes stack traces hard to read. If you need readable names in production (for error reports), disable only identifiers.

Source maps

A source map links the minified output back to your original files, so error stack traces and browser DevTools show real file names and lines.

Terminal
bun build ./src/index.ts --outdir ./dist --sourcemap=linked
Value Result
none No map (default).
linked Writes index.js.map and adds a //# sourceMappingURL= comment.
external Writes the map file but no comment (you wire it up yourself).
inline Embeds the map in the output file as a base64 data URL (large).

linked is the usual choice. Upload maps to your error-tracking service and keep them off the public server if you do not want visitors reading your original source.

Code splitting

When several entry points (pages) share modules, or when you load some code lazily with import(), splitting puts the shared code in separate chunks so it is downloaded once and cached.

Terminal
bun build ./src/home.ts ./src/about.ts --outdir ./dist --splitting
TypeScript
await Bun.build({
  entrypoints: ["./src/home.ts", "./src/about.ts"],
  outdir: "./dist",
  splitting: true,
});

Splitting requires --outdir and the ES module format. A dynamic await import("./chart") also becomes its own chunk, loaded when it runs. The trade-off is more requests; the gain is that rarely used code (a chart library) does not slow the first page load.

flowchart TD
  H["home.ts entry"] --> S["chunk-shared.js"]
  A["about.ts entry"] --> S
  H -. "import() on click" .-> C["chunk-chart.js"]

Shared code lives in one chunk; lazily imported code in another.

External packages

By default Bun bundles your dependencies. Sometimes you want them left as import statements for the runtime to resolve:

Terminal
bun build ./src/server.ts --outdir ./dist --target bun --external react --external "@aws-sdk/*"
bun build ./src/server.ts --outdir ./dist --target bun --packages external
  • --external name keeps one package (wildcards allowed) as an import.
  • --packages external leaves all bare package imports external, so only your own code is bundled and you ship with node_modules. This is common for server builds and libraries.

Peer dependencies and packages with native add-ons (.node files) generally should be external.

define: replace constants at build time

--define replaces identifiers with literal values, which also enables dead-code removal:

Terminal
bun build ./src/index.ts --outdir ./dist --define 'process.env.NODE_ENV="production"' --define 'VERSION="1.4.0"'
TypeScript
await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  define: {
    "process.env.NODE_ENV": JSON.stringify("production"),
    VERSION: JSON.stringify("1.4.0"),
  },
});

The value is source code, so strings need their own quotes (JSON.stringify does that). With NODE_ENV set to "production", a check like if (process.env.NODE_ENV !== "production") { devOnly() } is evaluated at build time, and the whole branch disappears from the bundle.

This stand-in shows the effect with a simple text replacement and a visible branch removal:

Node.js Stand-in: define and dead-code removal (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.

Environment variables in bundles

Bundling for the browser must not leak secrets. Bun inlines environment variables only when you ask:

Terminal
bun build ./src/index.ts --outdir ./dist --env "PUBLIC_*"   # inline matching variables only
bun build ./src/index.ts --outdir ./dist --env inline        # inline all (dangerous)
bun build ./src/index.ts --outdir ./dist --env disable       # inline none
TypeScript
await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  env: "PUBLIC_*",
});

With PUBLIC_*, a reference to process.env.PUBLIC_API_URL becomes its literal value, while process.env.DATABASE_PASSWORD is left alone. Convention: only variables meant for the browser get the PUBLIC_ prefix, and nothing secret ever does.

Naming and hashing

By default entry output is named after the entry file. To make files cache-safe, add a content hash that changes when the content does:

Terminal
bun build ./src/index.ts --outdir ./dist \
  --entry-naming "[dir]/[name]-[hash].[ext]" \
  --chunk-naming "chunks/[name]-[hash].[ext]" \
  --asset-naming "assets/[name]-[hash].[ext]"
TypeScript
await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  naming: {
    entry: "[dir]/[name]-[hash].[ext]",
    chunk: "chunks/[name]-[hash].[ext]",
    asset: "assets/[name]-[hash].[ext]",
  },
});

Placeholders: [name], [ext], [hash], [dir]. Hashed names let a CDN cache files for a year, because a change produces a new name. The returned outputs give you the final paths, which you need to write into an HTML file.

publicPath is a prefix for URLs of assets and chunks (for example https://cdn.example.com/):

TypeScript
await Bun.build({ entrypoints: ["./src/index.ts"], outdir: "./dist", publicPath: "https://cdn.example.com/" });

Format

Terminal
bun build ./src/index.ts --outdir ./dist --format esm   # default
bun build ./src/index.ts --outdir ./dist --format cjs
bun build ./src/index.ts --outdir ./dist --format iife  # self-running script for old <script> tags

ES modules suit modern browsers and Bun; cjs for libraries consumed by older Node tools. Libraries often publish both.

TypeScript
await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  drop: ["console", "debugger"],   // delete these calls from the output
  banner: "/* My App v1.4.0 */",
  footer: "// built by Bun",
});

drop: ["console"] removes console.* calls, handy for production browser bundles. Use it carefully: a call with side effects inside its arguments is dropped as well.

Everything together

A production build script:

TypeScript
// scripts/build.ts
const result = await Bun.build({
  entrypoints: ["./src/main.tsx"],
  outdir: "./dist",
  target: "browser",
  minify: true,
  sourcemap: "linked",
  splitting: true,
  env: "PUBLIC_*",
  define: { "process.env.NODE_ENV": '"production"' },
  naming: "[dir]/[name]-[hash].[ext]",
});

if (!result.success) {
  console.error(result.logs.join("\n"));
  process.exit(1);
}

const sizes = result.outputs.map((o) => `${o.path} ${(o.size / 1024).toFixed(1)} kB`);
console.log(sizes.join("\n"));

Run with bun run scripts/build.ts from a build script. Next you will learn how non-JavaScript files are handled in Loaders and HTML entry points.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which sourcemap value writes a .map file and adds a link comment to the bundle?

    linked creates the .map file and a sourceMappingURL comment so DevTools can find it.
  2. 2. What does --external react do?

    External packages are not included in the bundle; the runtime must resolve them.
  3. 3. Why does a define value usually need JSON.stringify for strings?

    define replaces identifiers with code. The text production would be an identifier; "production" is a string literal.
  4. 4. How do you avoid leaking secrets when bundling for the browser?

    Only variables matching the prefix are inlined, so secrets without the prefix stay out of the bundle.

Summary

  • --minify (or its three parts) shrinks output; --sourcemap=linked keeps debugging possible.
  • --splitting extracts shared and lazily loaded code into chunks (ES modules, with --outdir).
  • --external and --packages external keep dependencies out of the bundle.
  • --define replaces constants (and removes dead branches); --env "PUBLIC_*" inlines only safe variables.
  • naming with [hash] gives cache-friendly file names; format, drop, banner and footer tune the rest.

Next: Loaders and HTML Entry Points