Bun Compile — Single-File Executables
Ship your TypeScript CLI as one self-contained binary with bun build --compile: real benchmarks, cross-compilation targets, and the bunfs gotchas to know.
You wrote a CLI tool in TypeScript. It works great on your machine. Now you want to hand it to a user — and that user does not have Node.js, does not have Bun, and does not want to run npm install before they can use your tool.
That is the problem bun build --compile solves. One command, one file, and the result runs on a machine that has nothing installed.
bun build --compile ./cli.ts --outfile myclibashThat is genuinely all it takes. But there are real numbers, real trade-offs, and a couple of genuine gotchas behind that one-liner — and this post is about all three.
[!NOTE] Every number and behaviour below was measured locally with Bun 1.4.3 on macOS arm64 (Apple Silicon), not copied from a blog post. The commands are reproducible.
What a “single-file executable” actually is (ELI5)#
Think about cooking dinner for a friend.
- The normal way: you hand them a recipe (your
.tsfiles), a shopping list (package.json), and instructions to go to the supermarket first (npm install). They need a kitchen (Node.js or Bun) that works, plus internet access, plus time. Three things can go wrong. - The compiled way: you cook the whole meal, seal it in a container, and hand it over. They open it and eat. There is no kitchen to prepare, no shopping to do.
bun build --compile is that container. The output is a native binary containing three things:
- Your code, bundled and tree-shaken.
- Every npm package you imported.
- A full copy of the Bun runtime, including JavaScriptCore.
The important consequence: the size of the output is dominated by the runtime, not by your code. We measured this below.
The baseline: what one command produces#
#!/usr/bin/env bun
import { $ } from "bun";
const args = Bun.argv.slice(2);
console.log("args:", args);
console.log("bun version:", Bun.version);
if (args[0] === "pkg") {
console.log((await $`echo bundled-ok`.text()).trim());
}tsbun build --compile ./cli.ts --outfile ./myclibashMeasured output on Bun 1.4.3 / macOS arm64:
[27ms] bundle 1 modules
[260ms] compile ./myclitextThen:
$ ./mycli hello world
args: [ "hello", "world" ]
bun version: 1.4.3
$ ./mycli pkg
args: [ "pkg" ]
bun version: 1.4.3
bundled-okbashA ~300 ms build, and the result is a 67.6 MB binary that runs on a machine with nothing installed.
The numbers that matter#
Size: the runtime is the payload#
| Build flags | Binary size | Notes |
|---|---|---|
--compile | 67.6 MB (70,862,450 bytes) | Baseline on macOS arm64 |
--compile --minify | 67.6 MB | Identical — your code is a rounding error next to the runtime |
--compile --minify --sourcemap --bytecode | 67.6 MB | Same size; see the bytecode caveat below |
--minify shrank nothing here, and that is not a bug. If your app is 3 KB of source, minifying it saves maybe 1 KB out of 67.6 MB. Minify matters when you are bundling megabytes of dependencies — it just is not the lever people expect it to be here.
[!TIP] If binary size is your problem,
--minifyis not the answer. The lever is the runtime, and you cannot remove it from a--compilebuild. Ship a Docker image with a shared base layer, or publish to npm and let the user’s runtime handle it.
Startup: the win scales with your app#
We measured 20 runs of each command (after 3 warmup runs) on the same machine:
| Command | Time per run |
|---|---|
node -e "console.log('x')" | 26.7 ms |
bun run simple.ts (1 module) | 6.9 ms |
| compiled (1 module) | 6.1 ms |
bun run index.ts (400 modules) | 15.7 ms |
| compiled (400 modules) | 9.6 ms |
Read this honestly, because the headline is easy to oversell:
- For a one-file script, compiling saves about 0.8 ms. Process spawn dominates; there is almost nothing to win.
- For an app with 400 real modules, compiling saves 6.1 ms — a 39% reduction in wall-clock startup.
The reason is exactly what the Bun docs describe: normally Bun reads files from disk, resolves paths, parses, and transpiles on every startup. --compile moves that cost to build time. The more code you have, the more there is to move.
[!WARNING] Do not quote “compiled binaries start instantly” without qualifying it. The honest statement is: the more code you bundle, the more startup you save — and for trivial scripts the difference is within noise.
Cross-compilation: build once, ship everywhere#
You do not need a Linux machine to produce a Linux binary. Pass --target:
# Linux x64 (most servers)
bun build --compile --target=bun-linux-x64 ./index.ts --outfile myapp
# Linux ARM64 (Graviton, Raspberry Pi)
bun build --compile --target=bun-linux-arm64 ./index.ts --outfile myapp
# Windows x64 / ARM64 (.exe is added automatically)
bun build --compile --target=bun-windows-x64 ./src/cli.ts --outfile myapp
bun build --compile --target=bun-windows-arm64 ./src/cli.ts --outfile myapp
# macOS
bun build --compile --target=bun-darwin-arm64 ./src/cli.ts --outfile myapp
bun build --compile --target=bun-darwin-x64 ./src/cli.ts --outfile myappbashSupported targets:
--target | OS | Arch | libc |
|---|---|---|---|
bun-linux-x64 | Linux | x64 | glibc |
bun-linux-arm64 | Linux | arm64 | glibc |
bun-linux-x64-musl | Linux | x64 | musl |
bun-linux-arm64-musl | Linux | arm64 | musl |
bun-windows-x64 | Windows | x64 | — |
bun-windows-arm64 | Windows | arm64 | — |
bun-darwin-x64 | macOS | x64 | — |
bun-darwin-arm64 | macOS | arm64 | — |
We cross-compiled from an Apple Silicon Mac to Linux x64 and got a real ELF binary:
bun build --compile --target=bun-linux-x64 ./cli.ts --outfile ./app-linux-x64
[3.482s] compile ./app-linux-x64 bun-linux-x64-v1.4.3
$ file ./app-linux-x64
ELF 64-bit LSB executable, x86-64, dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2textThe musl target gives you a binary for Alpine containers:
$ file ./app-musl
ELF 64-bit LSB executable, x86-64, dynamically linked, interpreter /lib/ld-musl-x86_64.so.1text[!NOTE] The first cross-compile downloads the target runtime (about 40 MB in our run) and takes ~3.5 s. After that it is cached, and the build is fast. On CI, cache
~/.bun/install/cacheto avoid re-downloading on every job.
The flags that actually change behaviour#
--define — build-time constants#
bun build --compile --define BUILD_VERSION='"1.2.3"' --define BUILD_TIME='"2024-01-15T10:30:00Z"' \
src/cli.ts --outfile myclibashconsole.log(BUILD_VERSION); // 1.2.3
console.log(typeof BUILD_VERSION); // stringtsBun inlines these at build time, so they cost nothing at runtime and enable dead-code elimination.
--sourcemap — stack traces that point at your source#
This one matters more in a compiled binary than you might expect, because without it your stack traces point into a virtual filesystem.
With --sourcemap=linked:
error: kaboom from original source
at boom (crash.ts:2:9)
at crash.ts:4:1textWithout it:
error: kaboom from original source
at boom (/$bunfs/root/crash2:4:9)
at /$bunfs/root/crash2:6:5textSame bug, same message — but only the first version tells you which file and line to open. Always use --sourcemap for anything you ship.
--bytecode — and the top-level-await bug#
--bytecode moves JavaScriptCore’s parsing work from runtime to build time. We found a reproducible problem with it on Bun 1.4.3:
const v = await Promise.resolve(42);
console.log("tla:", v);ts$ bun build --compile --bytecode --outfile ./b-tla ./tla.ts
1 | const v = await Promise.resolve(42);
^
error: "await" can only be used inside an "async" function
at /private/tmp/bcompile/tla.ts:1:17
1 | const v = await Promise.resolve(42);
^
error: Unexpected .
at /private/tmp/bcompile/tla.ts:1:24bash$ bun build --compile --outfile ./b-tla-nobc ./tla.ts # same file, no --bytecode
[2ms] bundle 1 modules
[171ms] compile ./b-tla-nobc
$ ./b-tla-nobc
tla: 42bashSo: top-level await + --bytecode fails to build, reproducibly (2 out of 2 attempts), while the same file builds and runs fine without --bytecode. A script with no top-level await compiles with --bytecode without complaint.
[!WARNING] If your entrypoint uses top-level
await(very common withawait Bun.$,await Bun.file(...), or a top-levelfetch), do not enable--bytecodeon Bun 1.4.3. Check your own entrypoint before you ship a build that will not compile.
--compile-exec-argv — bake in runtime flags#
bun build --compile --compile-exec-argv="--smol --user-agent=MyBot" ./app.ts --outfile myappbashconsole.log(process.execArgv); // ["--smol","--user-agent=MyBot"]tsYou can also change flags at runtime without recompiling, using the BUN_OPTIONS environment variable:
BUN_OPTIONS="--cpu-prof" ./myappbashThe bunfs gotcha — the one that will surprise you#
Once your code is inside a binary, there is no longer a src/ folder on disk. Bun exposes the embedded files through a virtual filesystem called bunfs, mounted at /$bunfs/root.
We ran a compiled binary and printed the paths:
import.meta.path: /$bunfs/root/mycli
import.meta.dir: /$bunfs/root
execPath: /private/tmp/bcompile/myclitextThree consequences:
import.meta.pathis not a real path. Any code that opens files relative to its own location will break. Useprocess.execPathif you need the real path of the binary.- Your
import.meta.dirpoints intobunfs. It is the right place to look for embedded assets, but not the right place to write scratch files. - Embedded assets are addressed by their bunfs path. Bun hashes the filename, so you cannot guess it.
Reading embedded files — the import attributes matter#
import assetPath from "./asset.txt" with { type: "file" };
import readmeText from "./README.txt" with { type: "text" };tsNote that these are two different files. That is not accidental — see the warning just below.
These two lines are not interchangeable:
// with { type: "file" } → you get a PATH, not the content
console.log(assetPath); // "/$bunfs/root/asset-b45kncad.txt"
console.log(await Bun.file(assetPath).text()); // "embedded-asset-content"
// with { type: "text" } → you get the CONTENT directly
console.log(readmeText); // "Hello from README"tsIf you want to iterate over every embedded file, use Bun.embeddedFiles — it is an array of Blob objects:
for (const blob of Bun.embeddedFiles) {
console.log(blob.size, blob.type); // 23 text/plain;charset=utf-8
console.log(await blob.text()); // "embedded-asset-content"
}ts[!TIP] The
type: "file"vstype: "text"distinction trips up almost everyone. If you only need the contents, usetype: "text". Reach fortype: "file"only when you want to pass the path to something that expects a real file —Bun.file(),Bun.serve(), or a native library.
Never import the same file twice#
There is one more subtle trap. If you import the same file twice with two different attributes, Bun merges them into a single module — and the attribute of the first import wins, then applies to both bindings:
// "text" import first → both bindings are CONTENT
import a from "./asset.txt" with { type: "text" };
import b from "./asset.txt" with { type: "file" };
console.log(JSON.stringify([a, b])); // ["embedded-asset-content\n","embedded-asset-content\n"]
// "file" import first → both bindings are PATHS
import c from "./asset.txt" with { type: "file" };
import d from "./asset.txt" with { type: "text" };
console.log(JSON.stringify([c, d])); // ["/$bunfs/root/asset-b45kncad.txt","/$bunfs/root/asset-b45kncad.txt"]ts[!WARNING] Measured on Bun 1.4.3: in each pair, both variables get the same kind of value — either a path or the contents, depending on which import came first. If you need both, import that asset from two separate modules, or walk
Bun.embeddedFiles.
Full-stack executables#
--compile also bundles frontend assets. Import your HTML and Bun embeds it, together with the CSS and JS it references:
import { serve } from "bun";
import index from "./index.html";
const server = serve({
routes: {
"/": index,
"/api/hello": { GET: () => Response.json({ message: "Hello from API" }) },
},
});
console.log(`Server running at http://localhost:${server.port}`);tsbun build --compile ./server.ts --outfile myappbashWe ran it — the server started, assigned a port, and served the embedded frontend with correct MIME types and cache headers. One file, server plus client, deployable anywhere.
Your CLI can also be Bun#
Since Bun 1.2.16, an executable can fall back to the full Bun CLI:
BUN_BE_BUN=1 ./myapp installbashWe verified it: a binary compiled from a script that prints "you should not see this" printed exactly that when run normally, and printed the real Bun version when BUN_BE_BUN=1 was set. This is how you ship a CLI that can also install packages, bundle dependencies, or run other files — without shipping a second binary.
What about npm dependencies?#
They are bundled. We compiled a script that imports picocolors, then moved node_modules out of the way and ran the binary again:
colored: hello-from-a-npm-packagetextIt still worked. The binary needs nothing on the target machine — not even the dependency folder.
When you should not compile#
Compiling is not free, and it is not always the right answer:
Practical warnings:
- macOS Gatekeeper. Unsigned binaries downloaded from the internet get quarantined and blocked until the user approves them. Ship a signed binary or tell users how to approve it.
- Docker images. A 67 MB binary copied into every image layer bloats the image. A slim runtime base layer often wins.
- Native addons. A
.nodeaddon compiled for your build machine is still a compiled binary; cross-compiling does not cross-compile native C++ addons. This is the main reason to keep--targetbuilds in CI on the target architecture. - Frequent updates. Shipping a 67 MB file on every release is slower than publishing a small package to npm.
The Bun.build() API#
Everything above is available programmatically too, which is what you want in a build script:
const result = await Bun.build({
entrypoints: ["./cli.ts"],
compile: {
outfile: "./mycli",
target: "bun-linux-x64",
},
define: {
BUILD_VERSION: JSON.stringify("1.2.3"),
},
minify: true,
sourcemap: "linked",
bytecode: true,
});
console.log(result.success, result.outputs.length);tsTL;DR#
# One file, runs anywhere
bun build --compile ./cli.ts --outfile mycli
# Cross-compile from your laptop
bun build --compile --target=bun-linux-arm64 ./cli.ts --outfile mycli
# What we ship
bun build --compile --minify --sourcemap=linked ./cli.ts --outfile myclibash- The output is 67.6 MB on macOS arm64 — that is the Bun runtime, not your code.
--minifywill not shrink it. - Startup savings scale with code size: ~0.8 ms for a one-file script, 6.1 ms (39%) for a 400-module app.
import.meta.pathinside a compiled binary is/$bunfs/root/<name>. Useprocess.execPathfor the real path.with { type: "file" }gives you a path;with { type: "text" }gives you the content.- Never import the same asset twice — the first import’s attribute wins and applies to both bindings.
- Avoid
--bytecodeif your entrypoint uses top-levelawait— it fails to build on Bun 1.4.3. - Always ship
--sourcemap; without it, stack traces point into/$bunfs/rootinstead of your source.