Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 39 ยท Bundler and Transpiler

Single-File Executables

Turn a Bun program into one standalone executable with bun build --compile - cross-compile for Linux, macOS and Windows, embed assets, set minify and bytecode, and know the size and limits.

Sharing a command-line tool normally means telling users to install a runtime first. Bun can remove that step: bun build --compile bundles your code and a copy of the Bun runtime into a single executable file. The result runs on a machine that has neither Bun nor Node installed, starts quickly, and can be copied, downloaded or dropped into a Docker image on its own.

This lesson builds a small CLI, compiles it, targets other operating systems, embeds data files, and explains the trade-offs. The commands are read-only because the page cannot run Bun; a stand-in lets you test the program logic.

Write something worth shipping

A tool that greets people and reports a file's line count:

TypeScript
// src/cli.ts
import { parseArgs } from "node:util";

const { values, positionals } = parseArgs({
  args: Bun.argv.slice(2),
  options: {
    help: { type: "boolean", short: "h" },
    lines: { type: "boolean", short: "l" },
  },
  allowPositionals: true,
});

if (values.help || positionals.length === 0) {
  console.log("Usage: lines [--lines] <file>");
  process.exit(values.help ? 0 : 1);
}

const path = positionals[0];
const file = Bun.file(path);

if (!(await file.exists())) {
  console.error(`File not found: ${path}`);
  process.exit(2);
}

const text = await file.text();
const count = text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
console.log(values.lines ? `${count}` : `${path}: ${count} lines`);

Test it with the runtime first: bun src/cli.ts README.md. The program is ordinary Bun code; compilation changes only how it is packaged.

Compile it

Terminal
bun build --compile ./src/cli.ts --outfile lines

This writes an executable named lines (on Windows, lines.exe). Run it directly:

Terminal
./lines README.md
./lines --lines README.md

It does not need Bun on the machine. Under the hood Bun bundles your TypeScript and every imported package into JavaScript, then appends the result to a copy of the Bun runtime binary. When you start the file, it detects the embedded program and runs it.

Add the usual optimisations for a release build:

Terminal
bun build --compile --minify --sourcemap ./src/cli.ts --outfile lines
  • --minify makes the embedded code smaller.
  • --sourcemap keeps readable stack traces for crash reports.
  • --bytecode (in versions that offer it) precompiles JavaScript to bytecode so start-up is faster, at the cost of a larger file.

From code:

TypeScript
await Bun.build({
  entrypoints: ["./src/cli.ts"],
  compile: {
    outfile: "./dist/lines",
  },
  minify: true,
});

The compile option in the JavaScript API exists in recent versions and also accepts a target; for older versions, shell out to bun build --compile with Bun.$.

Cross-compiling

You can build for other platforms from one machine, with no need for a Windows or macOS computer:

Terminal
bun build --compile --target=bun-linux-x64     ./src/cli.ts --outfile dist/lines-linux-x64
bun build --compile --target=bun-linux-arm64   ./src/cli.ts --outfile dist/lines-linux-arm64
bun build --compile --target=bun-darwin-arm64  ./src/cli.ts --outfile dist/lines-macos-arm64
bun build --compile --target=bun-darwin-x64    ./src/cli.ts --outfile dist/lines-macos-x64
bun build --compile --target=bun-windows-x64   ./src/cli.ts --outfile dist/lines-windows-x64
Target Platform
bun-linux-x64, bun-linux-arm64 Linux (glibc)
bun-linux-x64-musl, bun-linux-arm64-musl Alpine and other musl distributions
bun-darwin-x64, bun-darwin-arm64 macOS Intel and Apple silicon
bun-windows-x64 Windows

Bun downloads the matching runtime on first use. For older CPUs without modern instructions use the -baseline variant (for example bun-linux-x64-baseline); the -modern variants target recent CPUs for slightly better speed. A release script can loop over a list of targets and upload each file.

On macOS, executables downloaded from the internet may need code signing and notarization to avoid a Gatekeeper warning. Windows executables can be given an icon and metadata with extra flags (see bun build --help). Signing is a distribution step outside Bun.

Embedding files

An executable is one file, so reading assets next to it would defeat the purpose. Embed them. Import with the file type and open the result with Bun.file:

TypeScript
import template from "./template.html" with { type: "file" };
import schema from "./schema.json";   // JSON is bundled as data already

const html = await Bun.file(template).text();
console.log(html.length, Object.keys(schema));

When compiled, the file is stored inside the executable and exposed through a virtual path (it looks like /$bunfs/root/template-abc123.html). Bun.file reads it from there, and Bun.embeddedFiles lists everything embedded. The same program works unchanged under bun run, where the import is a normal path.

Anything that is imported is embedded: JSON, TOML, text, images, SQLite databases (with { type: "sqlite" }) and WebAssembly. What is not embedded: files you only reference by a runtime path string (Bun.file("./data.csv") reads the real file system when the program runs).

You can even embed a static site and serve it with Bun.serve; that way the whole web app ships as one file.

Paths, arguments and environment

  • Bun.argv and process.argv work as usual: arguments you type after the executable name arrive after the first two entries.
  • import.meta.dir points inside the virtual file system; use it only for embedded files. For the executable's own location use process.execPath.
  • Environment variables work normally, and the executable can read .env files in the current directory at start-up, so a user can configure it without rebuilding.
  • Native add-ons (.node files) can be embedded when imported statically.

Size, speed and limits

A compiled executable includes the whole runtime, so it is large compared with a script: tens of megabytes (often around 50 to 100 MB) even for hello world. That is the price of needing nothing else installed. Tips:

  • Strip what you do not need: avoid pulling in huge dependencies, use --minify.
  • Compress for download (tar.gz or zip shrink it a lot).
  • Do not expect a smaller size than a Node SEA or Go binary; do expect fast start-up and a very simple developer experience.

Limits to remember:

  • Cross-compiling and some target options need a recent Bun version.
  • The executable embeds your source (bundled and optionally minified), not secret-proof machine code. Do not put API keys inside.
  • Dynamic import() or require() with computed paths cannot find files that were not bundled; list them as entry points or embed them.
  • Behaviour that depends on node_modules at run time (native modules loaded dynamically) needs extra care.

Release checklist

  1. Run the tests: bun test.
  2. Compile for each platform with --minify --sourcemap.
  3. Run the executable on a machine without Bun to confirm it is self-contained.
  4. Name files clearly (lines-linux-x64) and attach checksums.
  5. Document how to verify and run it in the README.

A stand-in for the CLI logic

The compiled program is the same code as the script, so test the logic in isolation. The stand-in below extracts the counting and argument handling into functions that accept data, the pattern that makes a CLI easy to unit test:

Node.js Stand-in: testable CLI logic (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.

The exit codes (0 success, 1 usage, 2 missing file) are the contract your CLI offers to shell scripts, which is just as important as the text it prints.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does bun build --compile produce?

    The compile step appends your bundled program to a copy of the Bun runtime, giving one file that runs without Bun installed.
  2. 2. Which flag builds a Windows executable from a Linux machine?

    Cross-compilation uses --target with names like bun-windows-x64, bun-linux-arm64 or bun-darwin-arm64.
  3. 3. How do you make a data file part of the executable?

    Imported files are embedded. A plain runtime path string reads from the real file system instead.
  4. 4. Why are compiled executables tens of megabytes even for tiny programs?

    Self-contained means the runtime is part of the file.

Summary

  • bun build --compile ./cli.ts --outfile name bundles your program with the Bun runtime into one executable.
  • --target=bun-<os>-<arch> cross-compiles for Linux, macOS and Windows (plus musl, baseline and modern variants).
  • Imported assets (with { type: "file" }, JSON, SQLite databases) are embedded; paths read at run time are not.
  • Use --minify and --sourcemap for releases; expect files of tens of megabytes.
  • Keep logic testable, define exit codes, and never embed secrets.

Next: Your First Server with Bun.serve