Ahead-of-time compilation
Compile TypeScript and JavaScript to machine code at build time, with bun compile
bun compile compiles your program to machine code at build time and writes one executable. It runs on machines that don't have Bun installed.
bun compile ./server.ts
./serverThere's no new syntax and nothing to annotate. TypeScript, JavaScript and npm packages all compile. Where your code has types, the compiler uses them to generate faster code.
What to expect#
Under bun run, and in an executable from bun build --compile, your code starts in an interpreter and a JIT compiles the hot functions while the program runs. bun compile does that work at build time. It follows the imports from your entry point, type checks your TypeScript, and works out which objects reach each variable and which function each call reaches. Then it generates machine code for every function the program can reach, npm packages included, and puts it into a copy of the Bun runtime. The executable has no JIT.
What you get:
- Your program starts faster. There's no source to parse and nothing to warm up.
- A large application uses less memory, and a tiny program uses about as much as without AoT. The process has no bytecode, no JIT-compiled code and no profiling data.
- Typed code runs faster. A property access is one load from a fixed offset, like a struct field in Go or Rust.
- A small program's file is smaller, because it leaves out the
buncommand line and the JIT. In a large program, the machine code can outweigh that.--trimremoves the Bun APIs you don't use.
What it costs:
- The build takes longer, and nothing is cached between builds.
- Untyped code can run slower than under the JIT. A JIT learns which objects show up at each property access by watching the program run. The compiler has to prove it at build time. Where it can't, the code looks the property up at run time.
bun compile --explainlists that code, worst first, with a fix for each. - A few things differ from
bun run.
When to stay with the JIT#
- Your hot code is untyped JavaScript from npm.
- You build on one platform and deploy to another.
bun compileonly builds for the platform it runs on, so run it in CI or in a container. - A library generates its hot code with
new Function, as some validators and serializers do. That code is interpreted. - A dependency replaces methods of built-in objects. Assigning to
Array.prototype.pushthrows aTypeError. - Your program spends its time in WebAssembly that it downloads or assembles at run time.
- You need breakpoints in the executable.
If you aren't sure, build both ways and put both under the same load. With --no-aot, the executable holds your JavaScript and runs it with the JIT.
bun compile --no-aot ./server.ts --outfile server-jit
bun compile ./server.ts --outfile server-aotBuild an executable#
bun compile ./server.ts --outfile serverawait Bun.build({
entrypoints: ["./server.ts"],
compile: { outfile: "./server", aot: true },
});bun compile is short for bun build --compile --aot and takes the same flags. Without an entry point, it builds the file that "bin" in package.json points to, then "module", then "main", then index.ts.
The entry point can also be the name of a command-line tool that an installed package provides. bun compile rollup builds the file that bun run rollup runs: the "bin" entry named rollup in node_modules/rollup/package.json, or else what node_modules/.bin/rollup points to. The build prints which file that is. A source file of that name in the working directory, such as rollup.ts, is compiled instead. bun build --compile rollup still resolves the name the way an import does, to the package's library.
If the package has no "bin" entry of that name, the build prints a note and compiles the package's library, which usually does nothing when it runs by itself.
Type errors stop the build#
const port: number = "3000";
console.log(port);bun compile ./wrong.ts1 | const port: number = "3000";
^
error: TS2322: Type 'string' is not assignable to type 'number'.
at /path/to/wrong.ts:1:7bun run removes your types and never checks them. bun compile relies on them, so it type checks the program first. If there's a type error, it writes no executable and exits with code 1.
bun check --aot reports the same errors and builds nothing. If you can't fix an error yet, you can suppress it.
The build only stops where tsc reports an error under your own tsconfig.json. Without a tsconfig.json, it uses the options of bun check.
| Code | Is it type checked? |
|---|---|
| A function that nothing calls | No, it isn't compiled. bun compile --check and bun check --aot check it too |
| JavaScript files | No, even with checkJs or // @ts-check. A syntax error still stops the build |
An entry point that exclude in tsconfig.json rules out, and what only it imports | No |
A folder whose tsconfig.json sets strictNullChecks or lib differently from the entry point's | No. The check line of the build counts its files as compiled without types |
During development, bun run --aot runs the same checks and then runs your program from its source. bun test --aot compiles your tests and runs the compiled code.
Harden the compiled code#
The compiler leaves out every check that it can prove isn't needed. If a proof were wrong, which would be a bug in Bun, the program could read or write memory that it shouldn't. So every build checks the type of a value where it enters a place whose type is proven, such as a parameter, a field or a variable. --aot-harden adds more checks, for programs that handle untrusted input.
bun compile ./server.ts --aot-harden=proof-checks,ignore-told-ranges| Name | What it adds | A tight loop over typed objects |
|---|---|---|
proof-checks | Checks the type again at each read, and checks again what the compiler remembers from earlier code. Objects stay on the heap, not on the stack | Runs about 5 times slower |
ignore-told-ranges | Checks every index against the length, where the index is used | Runs about 1.7 times slower |
A check that fails prints internal AOT error with the place in your code, then Bun's crash report, and aborts the process. The program can't catch it. Neither name is on by default, and neither changes what a correct program does. proof-checks tests what the compiler believes about values and runs the compiler's own verifier over the build. It doesn't find every compiler mistake. In Bun.build, pass compile: { aot: true, aotHarden: ["proof-checks"] }.
Order the executable by a recorded start#
--aot-order is profile-guided optimization (PGO) for how the executable is laid out. Run it once to record which functions a start uses, then build again with that profile. Bun places the machine code of those functions next to each other, and the strings, constants and object layouts they use too, so a cold start reads less of the file from disk.
In one large CLI application, cold start went from 1.67s to 0.69s and memory at startup dropped by 66 MB.
# 1. Build an executable that records
bun compile ./cli.ts --aot-record-order --outfile myapp-recording
# 2. Run it the way your users do
BUN_AOT_ORDER_OUT=myapp.order ./myapp-recording --help
# 3. Build again with the profile
bun compile ./cli.ts --aot-order=myapp.order --outfile myappWith Bun.build:
await Bun.build({
entrypoints: ["./cli.ts"],
compile: { aot: true, outfile: "./myapp", aotOrder: "./myapp.order" },
});- Record the start you want to speed up. A start of another kind gains less.
- Several profiles cover several ways of starting the app:
--aot-order=interactive.order,oneshot.order. List the most important one first. A function that more than one of them lists lies where the first one lists it. - Profiles keep working as your code changes. A function that is gone or renamed is skipped, and new code goes behind the recorded code. A build that differs in a version or a date alone, that runs in another folder, or whose files were moved or renamed, finds every function.
- Only an executable built with
--aot-record-ordercan record. Every other one has no recorder and reads no environment variable for it. - Only the layout changes. No function is compiled differently, and builds stay reproducible. The profile contains module paths and function names, not source code.
- On Linux, the executable asks for that part of the file when it starts, so a cold start waits for the disk once and not for one page after the other.
- A profile that can't be read is an error. A file that isn't a profile prints a warning, and nothing is placed by it. So does a profile of another program, which lists none of this program's functions. A profile that was cut off is used as far as it goes.
%pinBUN_AOT_ORDER_OUTbecomes the process id.Workerthreads are recorded too. A run that records is several times slower.- Recording works on Linux.
Read next#
- Types: how your types change the compiled program.
- Compatibility: what differs from
bun run. - Testing and debugging: stack traces, source maps and profilers.
- Troubleshooting: the errors you're most likely to hit first.
CLI Usage#
bun compile [flags] [entry point]bun compile takes every flag of bun build, and these. If package.json has a "compile" script, it runs that script instead.
The entry point is a file, or the name of a command-line tool of an installed package, such as rollup.
Output#
Write the executable to this path
The platform to build for, such as bun-linux-x64. bun compile only builds for the platform
it runs on. Add --no-aot to build for another one
Embed a file or directory into the executable, preserving its relative path. Can be repeated
Prepend arguments to the executable's process.execArgv
Compiling ahead of time#
Bundle the JavaScript into the executable instead of compiling it to machine code, like bun build --compile
List the code that compiled to a slow path, worst first, with a fix for each. --explain=json prints one
object per line. Other reports: guards, guards-json, trim,
allocations
Don't embed function source code. fn.toString() returns [native code]
Strip function names and source locations from the executable and write them to <outfile>.map. The
name of every function and class is empty
Let a debugger attach to the executable. Makes it larger and slower
Let import(), require() and new Worker() load code that isn't in the executable
from disk at run time. Makes it larger and slower
Lay the executable out by the order file that runs of it wrote (--aot-record-order), so that it starts
faster from a cold disk. Takes a list of files, most important first
Build an executable that writes an order file when it runs with BUN_AOT_ORDER_OUT
Make a bug in the compiler harder to turn into a memory bug. Takes a list of proof-checks and
ignore-told-ranges. The executable runs slower
Keep modules at their paths on disk and load anything that wasn't compiled from there. The executable only runs on the machine that built it
Remove the 32 GB heap limit per thread. The executable uses more memory and runs slower
In the executable, eval() and new Function() throw an EvalError.
=strict also blocks every other way to run code from a string
Size#
Remove the Bun and Node.js APIs your code never calls
Keep only these locales, such as en,de-AT. Implies --trim
Libraries#
bun compile --library [flags] [entry points]Builds a package to publish instead of an executable. Without an entry point, it builds the TypeScript files that "exports" in package.json points to. dependencies stay imports, and devDependencies are bundled.
Build a package to publish instead of an executable
The folder to write the package to. It cannot be the project's own folder
With --library: node, browser or bun
With --library: esm or cjs. A cjs package has no
.aot.ts files
Scripts#
Run this command even if package.json has a "compile" script