Compatibility

What behaves differently in an executable built with bun compile, and what to change in your program

Ahead-of-time compilation is experimental.

Most programs behave the same under bun compile as under bun run. The language, every node: and bun: module, Workers, native addons and nearly all npm packages work. This page lists what differs.

What differsWhat to do
Built-in objects are read-onlyAdd methods, don't replace them
Code from a string is interpretedKeep it out of hot paths
Unused built-ins are left outWrite the name of one that you need
A dynamic import finds only what the build foundStart the path with a folder, or pass the file as an entry point
Nothing hooks the module loaderUse paths in tsconfig.json
Your files are inside the executableEmbed what you read with --asset
Packages are bundled--main-fields, --ignore-dce-annotations
A few corners of the language follow the specRarely anything
Some flags and features aren't thereSee the table

The build also checks your types, and a type error stops it. To run your tests under the same rules, use bun test --aot.

Built-in objects are read-only#

Compiled code calls push directly. It doesn't check first whether something replaced it, so nothing can.

patch.js
Array.prototype.last = function () {
  return this[this.length - 1];
};
Array.prototype.push = function () {};
terminal
bun compile ./patch.js
4 | Array.prototype.push = function () {};
error: TS100014: this assignment always throws: built-in objects are read-only in a compiled executable

The first assignment is fine. It adds a method. The second replaces one, and since every run reaches it, the build stops. If the program might not get there, for example because the assignment is in a function, TS100014 is a warning and the assignment throws when it runs:

TypeError: Cannot assign to Array.prototype.push because built-in objects are read-only in a compiled executable

These work:

  • A new member: Array.prototype.last, String.prototype.shout, Math.tau, BigInt.prototype.toJSON, Map.prototype.toJSON, Error.prototype.toJSON.
  • A polyfill that checks first: Array.prototype.at ??= at.
  • A subclass: class List extends Array {}, class Upper extends Response {}.
  • What tests and tools usually replace: Date.now, Math.random, JSON.parse, JSON.stringify, fetch, the timers, console.*, process.exit, process.emit.
  • A global that isn't listed below: globalThis.Promise = Bluebird.
  • A symbol of your own, such as Symbol.for("nodejs.util.inspect.custom"), on any prototype but Object.prototype.
  • Object.freeze(Object.prototype).

These throw a TypeError:

  • Replacing, redefining or deleting a member that exists: Array.prototype.push = f, Object.defineProperty(Array.prototype, "push", d), delete Array.prototype.push. The same goes for Promise, Date, RegExp, Map, Set, Buffer, the typed arrays, Request, Response, Headers and URL, for createRequire of node:module, and for what process inherits, as in Object.getPrototypeOf(process).on = f.
  • Changing what one of these inherits from: Object.setPrototypeOf(Array.prototype, null).
  • Anything added to Object.prototype: Object.prototype.extra = 1.
  • Replacing a global that the language itself uses: globalThis.Array = List, globalThis.Map = Other.
  • What the language looks up by itself, added to a prototype that doesn't have it: Array.prototype[Symbol.toPrimitive], Array.prototype.then, Array.prototype.toJSON, RegExp.prototype.toJSON, Array.prototype[0].
  • process.versions, process.release and process.isBun, which tell a program what runtime it's on.

Reflect.set(), Reflect.defineProperty(), Reflect.deleteProperty() and Reflect.setPrototypeOf() return false for these, as they do for any read-only property.

Their property descriptors are what bun run reports, writable: true included. The exception is Buffer.concat, which reports writable: false. minizlib 3, which tar 7 and npm use, reads that descriptor and replaces the function only if it is writable.

The build has to see the assignment to Date.now, process.argv and the others that can be replaced. Spell out the object and the name. It can't see code from a string that it can't work out, so eval("Date.now = " + code) throws if your code uses Date.now.

If the line that throws is in a package, look the package up in Libraries.

Code from strings#

strings.ts
const add = new Function("a", "b", "return a + b");
const local = 5;
console.log(add(2, 3), eval("local * 2"), (0, eval)("typeof Bun"));
terminal
bun compile ./strings.ts && ./strings
5 10 object

eval, new Function and node:vm work, under a computed name like globalThis[name](code) too. The build can't see that code and the executable has no JIT, so Bun interprets it.

There's one exception. Some libraries make many similar functions from a template, as in eval(template.replace("NAME", "add")) or new Function("a", "b", "return a " + operator + " b"). Where the build can work out such strings from the constants of the file, and those that it imports from other files, it compiles the function. For eval the string has to be one function in parentheses. The executable uses the function where the strings turn out to be the same.

  • Where the build can't tell that a call evaluates code, the call throws an EvalError. fn[name](code) does if "constructor" isn't written anywhere in your code.
  • Code from a string can import() your entry points. Any other file may throw Cannot load. Pass the module to that code instead. From a JSON file in the executable it gets the default export. A named one throws a ReferenceError when it's read, unless an import of yours names it. new Function("path", "return import(path)") and eval("import('./a.js')"), with strings that are written out like that, are compiled as that import(). If your program has replaced eval or Function when such a call runs, the replacement is called where the build can see that you replace it (globalThis.eval = f, Object.assign(globalThis, { eval: f }), Object.defineProperty(globalThis, "eval", { value: f })). Otherwise the call throws an EvalError.
  • Code from a string finds the module of a file only if your own code uses one. If it doesn't, process.mainModule may be undefined, and what process.mainModule.children holds throws Cannot access the module object. Write void module.children; in one of your files.
  • A script from a string can't declare a built-in global at its top level. vm.runInThisContext("let Array = 5") throws a SyntaxError, and function Array() {} a TypeError. It works in a block, in a function or in a node:vm context of its own.

Interpreted code is fine for a template or a config file. It costs you when a library generates its hot code this way, as zod 4, ajv, fast-json-stringify and Elysia do.

  • zod 4: call z.config({ jitless: true }) before you create a schema.
  • Fastify: call app.setSerializerCompiler(() => JSON.stringify), and write the validators to files with the standalone mode of @fastify/ajv-compiler.

If your program needs no code from strings, build with --disallow-code-generation-from-strings. eval then throws an EvalError, and the compiler can optimize more.

ShadowRealm isn't supported. The build warns (TS100076), and new ShadowRealm() throws a ReferenceError. Use a node:vm context.

Unused built-ins#

An executable holds the parts of Bun's own JavaScript that your code uses. When code from a string uses another part, such as Bun.$ or a function of node:util, it gets an error that it can catch. Write void Bun.$ anywhere in your code to keep that part, or import the function by name.

Error: Bun.$ was not compiled into this executable because your code never uses it. To keep it, use it somewhere in your code.
Error: 'promisify' was not compiled into this executable because nothing that the compiler can follow calls it. To keep it, import it by name: import { promisify } from "node:util".

An event can lead to such a part too. Called without a receiver, dispatchEvent() and addEventListener() work on the global object, and event.target is the global object. The build follows that where your code writes the method's name. It doesn't if the name is only known at run time, as in const send = signal[process.env.METHOD]; send(event), or if it comes out of a for...in. Reading event.target.process.finalization then throws:

Error: process.finalization was not compiled into this executable because the compiler saw no use of it. Your code reached it through the `target` of an event on the global object. To keep it, write `void dispatchEvent` anywhere in your code.

Call the method with its receiver instead: signal[name](event). Or write void dispatchEvent, which keeps everything that the global object leads to and makes the executable about 3 MB larger.

WebAssembly#

A .wasm file that you import is compiled at build time. So is a module that's in your source as a base64 string, if you decode it with atob() or Uint8Array.fromBase64(). Bytes that your program downloads or assembles at run time are interpreted, and a tight loop in them runs much slower than under bun run.

Dynamic imports#

app.ts
const plugin = await import("./plugins/" + process.argv[2] + ".ts");
console.log(plugin.default);
plugins/hello.ts
export default "hello from a plugin";
terminal
bun compile ./app.ts && ./app hello
hello from a plugin

The build compiles every file it can reach from your entry point. Where a path isn't a constant, it uses the parts that are, and compiles every file that the path can name. It warns at each such path (TS100064). require() and new Worker() follow the same rules as import(). If you've checked a line and its warning doesn't apply, silence it with a comment.

PathWhat the executable holds
"./plugins/" + name + ".ts"plugins/*.ts
new URL(`./plugins/${name}.ts`, import.meta.url)The same
`@/plugins/${name}.ts`The same, with "paths": { "@/*": ["./*"] } in tsconfig.json
`locales/data/${name}.js`node_modules/locales/data/*.js
process.env.PLUGIN || "./plugins/a.ts"plugins/a.ts
path.join(process.env.DIR || __dirname, "a.ts")a.ts
"./locales/" + langCode and data files in locales/. --explain lists the data files (TS100088)
"./" + nameCode only. The build names the data files that it leaves out (TS100089)
"./" + name + ".json"The .json files
table[key], where table holds constant pathsThose files
nameNothing more. It finds your entry points, and a compiled file whose path is a string somewhere in your code
  • __dirname, import.meta.dir, import.meta.url, path.join(), new URL(), process.platform and process.arch count as constants, so the usual loader of a native addon works.
  • fs.readdirSync() and fs.existsSync() see the compiled files, so a loader that lists a folder and calls require() on each file works.
  • import.meta.glob() is expanded at build time, and every file that matches is compiled.
  • require.resolve() and import.meta.resolve() return a path. They don't embed the file. Neither do Bun.resolveSync(), Bun.resolve() and import.meta.resolveSync(). With those three the build warns if the path names a file that isn't in the executable (TS100099). require.resolve() returns where the file was when you built, so reading it fails on another machine.
  • require("./notes.txt") returns the text itself, as in bun build --compile. bun run returns an object with the text as its default.
  • An import() at the top level of an ES module that a require() loads, or of a CommonJS file that this module imports, runs its module after that require() returns, as in Node.js and bun build --compile. Under bun run, it runs during the require().
  • In a cycle of require() and import, a CommonJS file can be imported before it has finished, and again later. In the executable, every importer then sees the exports of the later import. Under bun run and with --no-aot, the first importer keeps what the file exported at that point.
  • A query, as in import("./a.ts?v=2"), loads one more copy of the file, as in bun run. ?worker works too. ?raw, ?url, a query on a data file and a query in a require() stop the build (TS100159).

A file that isn't in the executable#

You loadWhat happens
A relative path or a package name that the executable doesn't holdMODULE_NOT_FOUND, so try { require(optional) } catch {} works
A compiled file, by a path that the build knows nothing aboutCannot load '/$bunfs/root/lib/a.ts': this executable can't load a module from a dynamic path
A path made from the working directory, like path.resolve("lib/a.js")It names a file on disk. Use import.meta.dir or __dirname for a compiled file
An absolute path to code on diskCannot load '/home/me/late.ts': it isn't in this executable
An absolute path to JSON, TOML, YAML or text on diskThe file is read from disk
You want to loadDo this
One of your filesPass it as another entry point
A package with a dynamic namePass its main file as an entry point
A node: or bun: module with a dynamic nameImport it by name somewhere, if it throws Cannot load
A Worker that the build can't findPass it as another entry point. The build warns (TS100082)
JSON, TOML, YAML or text from diskGive an absolute path
Any code from disk--aot-allow-code-from-disk
One package from disk--external <package> --aot-allow-code-from-disk
terminal
bun compile ./app.ts './extra/*.ts' ./node_modules/pg/lib/index.js

Where the build can't tell which file a Worker starts from, it also compiles the files that your own code names: by a URL or a path that it makes from import.meta, or by a text such as "./jobs/resize.ts". A text only leads to files in the root directory, which is the folder of your entry point, the folder that several entry points share, or --root. The folder that you build in makes no difference. The build lists these files (TS100168), and --explain shows where each one is named (TS100167). If one can't be compiled, the build says so and goes on, and a Worker that loads it fails. Names that a package writes don't count.

Code that's loaded from disk is interpreted. It can use globals, built-in modules, files and packages on disk, and what your program passes to it. It can't import the files that were compiled into the executable, and a package that it imports is a second instance.

Next.js and Angular load your pages by dynamic paths. Libraries shows what to pass.

Loader hooks and the module cache#

Every import, and every require() of a constant path, is resolved at build time. Nothing in node:module runs on the way. An executable built with --no-aot is a bundle, and behaves the same.

In your programIn an executable
Module._resolveFilename = hookCalled for dynamic paths only. The build warns (TS100080)
Module._extensions[".js"] = loaderCalled for dynamic paths only. Can't change the source or run a file twice
delete require.cache[path], require.cache[path] = entryDo nothing. A module runs once. The build warns (TS100091, TS100092)
require.cache["url"] = entry, for a built-in moduleWorks if the key is written out. A computed one throws
Object.keys(require.cache)Doesn't list compiled modules
Bun.plugin() at run timeAsked about dynamic paths only. It can't replace a module that was compiled
A tracer that patches modules as they load, like OpenTelemetry'sSees none of them

For aliases, use paths in tsconfig.json or imports in package.json.

Paths of the running file#

Every compiled file has a path under /$bunfs/root, laid out like your sources.

In lib/inner.jsIn an executable
import.meta.urlfile:///$bunfs/root/lib/inner.js
import.meta.dirname, import.meta.dir/$bunfs/root/lib
import.meta.filename, import.meta.path/$bunfs/root/lib/inner.js
module.filename, module.id/$bunfs/root/lib/inner.js
process.argv[1], Bun.main/$bunfs/root/cli.js, your entry point
__dirname, __filenameWhere the file was when you built
process.execPathThe executable

/$bunfs/root is the folder of your entry point. A file above it, like a package in a node_modules beside src, is under /$bunfs/_.._ instead. For a folder more than one level above your entry point, use __dirname: path.join(import.meta.dir, "../../commands") is /commands in an executable.

A comparison of __filename with another path of the same file, like process.argv[1] === __filename, gives what it gives under bun run. It may go through variables, path.resolve(), path.dirname(), fs.realpathSync(), fileURLToPath(), pathToFileURL() and replace(). The two strings stay different: [__filename].includes(process.argv[1]) is false.

require.main === module, import.meta.main, module.paths, module.parent and createRequire(import.meta.url) work as under bun run.

An executable runs your entry point by itself, so a program that starts a copy of itself must not pass the file. Write spawn(process.execPath, ["child"]). After spawn(process.execPath, [process.argv[1], "child"]) or fork(__filename, ["child"]), the child finds the path in process.argv[2] and "child" in process.argv[3].

Files beside your code#

render.js
import fs from "node:fs";
console.log(fs.readFileSync(new URL("./template.html", import.meta.url), "utf8"));
template.html
<p>hello</p>
terminal
bun compile ./render.js --asset ./template.html && ./render
<p>hello</p>

That path is inside the executable, so the read only finds a file that's in there too. The build embeds what you import or require(), not what you read. Without --asset the read fails with ENOENT and fs.existsSync() returns false. Where the build can see the read, it warns and names the flag (TS100098). It also warns where your own code passes such a file or folder to code that may read it, as in express.static(path.join(__dirname, "public")) (TS100172), and where any code needs one on the disk, as in spawn("python3", [path.join(__dirname, "tool.py")]) (TS100173). Another program only finds what's on disk, and so do Bun.$, Bun.build(), fs.watch() and the cwd of a process, so ship that file beside the executable. After process.chdir(import.meta.dirname), relative paths find the embedded files.

Two kinds of files are embedded without the flag, where the build can see the read: a file inside a package in node_modules, such as the package's own package.json or a font, and the package.json nearest above your entry point. --explain lists them (TS100166), and also the files that a package's path leads to where the build doesn't see the read: a path that it exports or passes on, a folder that it lists, a file that it only tests for, or a path with an unknown part (TS100176). The metafile has each of these files among its inputs. A package in node_modules whose code reads, checks or lists files at paths that the build can't know, for example by searching the folders above it, or hands its own folder to code that may do so, gets its own package.json embedded too (TS100170). Where it hands on a folder from which a search finds a package.json that isn't embedded, such as path.join(__dirname, ".."), the build warns (TS100174). It also warns where a package hands on a folder to code that may list it, and the executable holds some of its files alone (TS100175). Code that searches upward finds the nearest package.json, as in plain Bun: where one is embedded this way, each one that lies nearer to compiled code is embedded as well (TS100171), in a folder of your own too, and so is each one in the folders below a package's own, and if one of those has to stay out, so does the one above it. A file that is only tested for, by existsSync, stat or access, takes no room: the executable knows that it exists and how large it is, and holds none of its bytes. A package.json is the exception and is embedded whole, because code that finds one reads it. A package is a folder directly below node_modules that has a package.json. A file reached through a symbolic link, a file or folder whose name begins with a dot, and a lock file always need the flag.

A read through __dirname finds the file on the machine that built the executable, and the embedded one anywhere else. Once your program removes or renames that file on disk, the embedded one is gone for it too. A file that was embedded without --asset is also gone where something else removed it and the executable runs beside its sources, which means that the code around that file is still on disk. Where that path's folder isn't on disk, the embedded file can be read and not changed: writing, renaming or removing it fails with ENOENT or EROFS, and so does writing a new file beside it. Make the folder with mkdirSync(folder, { recursive: true }) first. A listing of a folder that's on disk has only what's there. Writing a file there writes it on disk alone: appending to an embedded file that isn't on disk starts an empty file. By its path under import.meta.dirname, an embedded file is read-only. A Bun.file() object of an embedded file keeps the bytes it had when it was made, and can't be written through.

A path made from import.meta.dirname climbs at most one folder above the root of the executable. An asset that lies two or more folders above it is embedded, but such a path doesn't find it. Where the build can see the read, it warns (TS100087). __dirname finds it.

--asset follows no symbolic links inside a folder, so what they lead to isn't embedded. Where the build can see such a read, it warns and names the link to pass as an asset of its own (TS100165).

fs.stat() gives an embedded file the modification time that it had when you built. A file above the root of the executable has time 0, unless the program only asks about it and the executable holds its size alone. A folder is as new as the newest file in it that the executable holds, so two builds of the same files are identical.

Your own code is in there as machine code, not as text. fs.existsSync() finds a compiled file, but its size is 0 and reading it fails with ENOENT. A compiled file whose source was removed from disk isn't found where the executable runs beside its sources, which means that the file's folder and code around it are still on disk.

Some packages load their own files by a name that they put together when the program runs:

PackageIn an executableDo this
expressres.render() can't find the view engineapp.engine("ejs", require("ejs").__express), and --asset ./views
require-directoryThrows ENOENTPass the folder's files as entry points
pinopino.transport() fails to start its workerPass the three files below as entry points, or log without a worker
terminal
bun compile ./app.ts ./node_modules/thread-stream/lib/worker.js ./node_modules/pino/lib/worker.js ./node_modules/pino/file.js

pino(pino.destination(1)) writes the same lines without a worker.

Packages#

An executable is a bundle, so two fields of a package.json mean what they mean to bun build. bun run treats them differently.

"main" and "module"#

If a package has both, import loads "module" in an executable and "main" under bun run. require() loads "main" in both, and one require() of the package anywhere makes every import of it load "main" too. "exports" wins over both fields. bun test --aot loads "main", as bun test does.

The two files usually export the same things. If they don't, put "main" first:

terminal
bun compile ./app.ts --main-fields main --main-fields module

"sideEffects": false#

With that field, a package says that loading its files does nothing except define their exports. The build takes it at its word. bun run doesn't read the field.

In your programIn an executable
import "pure"Removed. The package's file never runs
import { x } from "pure", and nothing uses xRemoved
import { x } from "pure", and x is usedThe file runs
Any of these in an entry pointThe file runs
require("pure"), await import("pure")The file runs

A use in a function that nothing calls doesn't count. The field in your own package.json covers your own files, so import "./setup.ts" is removed too, except in an entry point. The entry points are the files that you build and the files that a Worker starts from.

If you import such a package for what it does when it loads, like a polyfill or a plugin that registers itself, its field is wrong. Build with --ignore-dce-annotations. zod@3.25.76 is such a package: after import * as z from "zod/v4", every message is Invalid input.

Language#

bun run transpiles each file before it runs it, and its transpiler takes a few shortcuts. Compiled code does what the language says, as Node does.

In your programbun runAn executable
{ function inner() {} } in a CommonJS file that isn't in strict modeinner stays inside the blockinner is visible after it
const first = read(), limit = 5, where read() returns limit5A ReferenceError
undefined[key] = 1, where key has a toString()Calls toString(), then throwsThrows
(Color as any).Red = 2, then Color.Red, for an enum imported from a file21. The member is a constant
"useDefineForClassFields" in tsconfig.jsonTaken from the one in the working directoryTaken from the one nearest to each file
fn.caller and fn.arguments, outside strict modeThe calling function and the argumentsnull. The build warns (TS100302)

process.env.NODE_ENV, process.platform and process.arch, written out like that, are replaced by their values when you build, as in bun build --compile. NODE_ENV=production ./app still reads "development" unless you built with NODE_ENV=production or --production.

An executable can collect an object earlier or later than bun run does. Only a WeakRef, a FinalizationRegistry or the size of the heap can tell. Keep a FinalizationRegistry at module level, so that it isn't collected before its callback runs.

Error messages#

Most errors that only compiled code throws end with a link to this page, and say what to write instead.

The class of an error and the lines in its stack trace are the same as under bun run, with two exceptions. A code file with a mistake that bun run's transpiler finds, such as a name that's declared twice, throws a SyntaxError instead of a BuildMessage. A frame shows the name that you wrote for a function, whatever Object.defineProperty(fn, "name", ...) set later. The paths in the stack trace are relative to the folder you ran the build in: ./src/server.ts:12:9. getFileName() of a call site, which packages use to find files, returns the path that import.meta.path has. An uncaught error prints without the source excerpt that bun run shows above it.

A message that quotes your code can differ. An executable quotes what you wrote, and leaves out functions and literals that span lines. bun run quotes what its transpiler printed.

Where a message quotes your source, an executable takes it from the text of your functions, which it keeps for fn.toString(). Built with --no-compile-function-source it has no text, and says less:

TypeError: null is not an object (evaluating 'o.a.c')
TypeError: null is not an object (evaluating 'null.c')       without the text

TypeError: s is not a function. (In 's()', 's' is "text")
TypeError: s is not a function. (In 's()', 's' is a string)  without the text

Check error.name or use instanceof, not error.message.

fn.toString() returns a function as you wrote it, without its types. bun run returns what its transpiler printed, so spaces, line breaks and comments differ. A function of Bun or of a node: module prints as function IncomingMessage() { [native code] }.

Not supported#

FeatureInstead
--target for another platformBuild on that platform, or pass --no-aot
--preload, --import in BUN_OPTIONSImport the file from your entry point, or build with --compile-inspector
preload in bunfig.tomlIt's ignored. Import the file from your entry point, or build with --compile-inspector
The same, built with --no-compile-function-source or --obfuscateIt's an error at startup. Build with --no-compile-autoload-bunfig
--inspect in BUN_OPTIONS, BUN_INSPECTBuild with --compile-inspector
--unhandled-rejections in BUN_OPTIONSBuild with --compile-exec-argv=--unhandled-rejections=<mode>
--sql-preconnect in BUN_OPTIONSBuild with --compile-exec-argv=--sql-preconnect
Breakpoints and debuggerbun --inspect-brk ./app.ts
cc() from bun:ffi, on Linux 6.7 and laterCompile the C file first, then dlopen()
Over 256 open JSCallbacks, if the executable can't read its own fileMake the file readable, or close() some
Over 32 GB of objects in a thread--aot-huge-heap
A stack under 512 KB (ulimit -s)Give it more. bun run needs less
with { type: "macro" } on an import (TS100053)Pass --no-aot