Bun Compile — 单文件可执行程序
用 bun build --compile 把 TypeScript CLI 打包成一个自包含的二进制文件:实测数据、跨平台编译目标,以及 bunfs 那些必须知道的坑。
你用 TypeScript 写了一个 CLI 工具,在自己机器上跑得非常好。现在你想把它交给用户 —— 而那位用户没有 Node.js,没有 Bun,也不想在用之前先跑一遍 npm install。
这正是 bun build --compile 要解决的问题。一条命令,一个文件,产物在什么都没装的机器上也能运行。
bun build --compile ./cli.ts --outfile myclibash真的就这么简单。但在这一行命令背后,有真实的数字、真实的取舍,以及几个真实的坑 —— 这篇文章会把这三样都讲清楚。
[!NOTE] 下面每一个数字和行为都是用 Bun 1.4.3 在 macOS arm64 (Apple Silicon) 上本地实测得到的,不是从别的博客里抄来的。所有命令都可以复现。
“单文件可执行程序”到底是什么?(ELI5)#
想象你给朋友做一顿晚饭。
- 常规做法: 你把食谱(你的
.ts文件)、购物清单(package.json),再附一句”请先去趟超市”一起给他。对方需要一间能用的厨房(Node.js 或 Bun)、需要网络、还需要时间。有三个地方可能出问题。 - 编译后的做法: 你把整道菜做好,装进密封的盒子里递过去。他打开就吃。不用准备厨房,也不用去采购。
bun build --compile 就是那个盒子。产物是一个 原生二进制文件,里面装着三样东西:
- 你的代码,已经打包并做了 tree-shaking。
- 你 import 的所有 npm 包。
- 一份完整的 Bun runtime 副本,包含 JavaScriptCore。
一个重要推论:产物体积由 runtime 主导,而不是你的代码。 下面我们会实测这一点。
基线:一条命令能产出什么#
#!/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 ./myclibash在 Bun 1.4.3 / macOS arm64 上实测:
[27ms] bundle 1 modules
[260ms] compile ./myclitext然后:
$ ./mycli hello world
args: [ "hello", "world" ]
bun version: 1.4.3
$ ./mycli pkg
args: [ "pkg" ]
bun version: 1.4.3
bundled-okbash构建大约 300 ms,产物是一个 67.6 MB 的二进制文件,在什么都没装的机器上照样能跑。
真正值得看的数字#
体积:runtime 就是负载本身#
| 构建参数 | 二进制体积 | 说明 |
|---|---|---|
--compile | 67.6 MB (70,862,450 bytes) | macOS arm64 上的基线 |
--compile --minify | 67.6 MB | 完全一样 —— 放在 runtime 旁边,你的代码只是舍入误差 |
--compile --minify --sourcemap --bytecode | 67.6 MB | 体积相同;bytecode 的坑见下文 |
这里 --minify 一点体积都没省下来,这不是 bug。如果你的应用只有 3 KB 源码,压缩后也就省下 67.6 MB 里大约 1 KB。minify 在打包几 MB 依赖时才有意义 —— 只是它在这里并不是大家以为的那个杠杆。
[!TIP] 如果体积是你的问题,
--minify不是答案。杠杆在 runtime 上,而你无法把它从--compile产物里去掉。要么用共享 base layer 的 Docker 镜像分发,要么发布到 npm,让用户自己的 runtime 来承担。
启动速度:收益随应用规模增长#
我们在同一台机器上,对每条命令先热身 3 次,再各跑 20 次取平均:
| 命令 | 每次耗时 |
|---|---|
node -e "console.log('x')" | 26.7 ms |
bun run simple.ts(1 个模块) | 6.9 ms |
| 编译后(1 个模块) | 6.1 ms |
bun run index.ts(400 个模块) | 15.7 ms |
| 编译后(400 个模块) | 9.6 ms |
请诚实地读这张表,因为它的标题很容易被夸大:
- 对单文件脚本,编译只省下约 0.8 ms。进程启动占了大头,几乎没有可省的余地。
- 对有 400 个真实模块的应用,编译省下 6.1 ms —— 启动时间减少 39%。
原因正是 Bun 官方文档描述的机制:平时 Bun 每次启动都要从磁盘读文件、解析路径、parse 并转译。--compile 把这份开销搬到了构建期。代码越多,能搬走的就越多。
[!WARNING] 不要不加限定地引用”编译后的二进制瞬间启动”这句话。诚实的说法是:你打包的代码越多,省下的启动时间越多 —— 而对微不足道的脚本来说,差异落在噪声范围内。
跨平台编译:构建一次,到处分发#
你不需要一台 Linux 机器才能产出 Linux 二进制。传 --target 就行:
# Linux x64(大多数服务器)
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 会自动加上)
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 myappbash支持的 target:
--target | 操作系统 | 架构 | 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 | — |
我们从 Apple Silicon 的 Mac 交叉编译到 Linux x64,拿到的确实是一个可用的 ELF 二进制:
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.2textmusl target 给你的是能在 Alpine 容器里跑的二进制:
$ file ./app-musl
ELF 64-bit LSB executable, x86-64, dynamically linked, interpreter /lib/ld-musl-x86_64.so.1text[!NOTE] 第一次交叉编译会下载对应 target 的 runtime(我们这次下载了约 40 MB),耗时约 3.5 秒。之后就会缓存,构建很快。在 CI 上请缓存
~/.bun/install/cache,避免每个 job 都重新下载。
真正会改变行为的参数#
--define —— 构建期常量#
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 会在构建时把这些值内联,运行时零开销,同时还能做死代码消除。
--sourcemap —— 指向原始源码的堆栈#
在编译后的二进制里,这个参数比你想的更重要,因为没有它,堆栈会指向一个虚拟文件系统。
加上 --sourcemap=linked:
error: kaboom from original source
at boom (crash.ts:2:9)
at crash.ts:4:1text不加:
error: kaboom from original source
at boom (/$bunfs/root/crash2:4:9)
at /$bunfs/root/crash2:6:5text同一个 bug,同一条消息 —— 但只有第一个版本能告诉你该打开哪个文件的哪一行。凡是分发出去的东西,请始终加上 --sourcemap。
--bytecode —— 以及 top-level await 的坑#
--bytecode 把 JavaScriptCore 的解析工作从运行时搬到构建时。我们在 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 # 同一个文件,不加 --bytecode
[2ms] bundle 1 modules
[171ms] compile ./b-tla-nobc
$ ./b-tla-nobc
tla: 42bash也就是说:top-level await 遇上 --bytecode 会构建失败,可稳定复现(2 次尝试 2 次失败),而同一个文件不加 --bytecode 就能正常构建并运行。不含 top-level await 的脚本用 --bytecode 编译则毫无问题。
[!WARNING] 如果你的入口文件用了顶层
await(用await Bun.$、await Bun.file(...)或顶层fetch都很常见),在 Bun 1.4.3 上不要开启--bytecode。在分发一个根本编译不过的产物之前,先检查自己的入口文件。
--compile-exec-argv —— 把运行时参数烤进二进制#
bun build --compile --compile-exec-argv="--smol --user-agent=MyBot" ./app.ts --outfile myappbashconsole.log(process.execArgv); // ["--smol","--user-agent=MyBot"]ts你也可以不重新编译、就在运行时改参数,用 BUN_OPTIONS 环境变量:
BUN_OPTIONS="--cpu-prof" ./myappbashbunfs 这个坑 —— 最让人意外的那个#
代码进入二进制之后,磁盘上就不再有 src/ 目录了。Bun 通过一个叫 bunfs 的 虚拟文件系统 暴露内嵌文件,挂载点是 /$bunfs/root。
我们运行了一个编译后的二进制并打印路径:
import.meta.path: /$bunfs/root/mycli
import.meta.dir: /$bunfs/root
execPath: /private/tmp/bcompile/myclitext三个直接后果:
import.meta.path不是真实路径。 任何相对于自身位置去打开文件的代码都会崩。需要二进制的真实路径时请用process.execPath。- 你的
import.meta.dir指向bunfs。 那里是找内嵌资源的正确位置,但不是写临时文件的地方。 - 内嵌资源要用 bunfs 路径来寻址。 Bun 会给文件名做哈希,所以你猜不出来。
读取内嵌文件 —— import attribute 很重要#
import assetPath from "./asset.txt" with { type: "file" };
import readmeText from "./README.txt" with { type: "text" };ts注意这里是 两个不同的文件。这不是随手写的,原因见下面的警告。
这两行 不能互换:
// with { type: "file" } → 你拿到的是路径,不是内容
console.log(assetPath); // "/$bunfs/root/asset-b45kncad.txt"
console.log(await Bun.file(assetPath).text()); // "embedded-asset-content"
// with { type: "text" } → 你直接拿到内容
console.log(readmeText); // "Hello from README"ts如果想遍历所有内嵌文件,用 Bun.embeddedFiles —— 它是一个 Blob 对象数组:
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]
type: "file"和type: "text"的区别几乎坑过所有人。你只需要内容时,用type: "text";只有当你需要把路径交给真正要求真实文件的东西时(Bun.file()、Bun.serve()或某个原生库),才用type: "file"。
不要把同一个文件 import 两次#
还有一个更隐蔽的坑。如果你用两个不同的 attribute 把 同一个文件 import 两次,Bun 会把它们合并成一个模块 —— 然后 第一个 import 的 attribute 胜出,并同时作用于 两个 变量:
// "text" import 在前 → 两个变量都是内容
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 在前 → 两个变量都是路径
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] 以上是在 Bun 1.4.3 上实测的结果:每一对里 两个 变量拿到的都是同一种东西 —— 是路径还是内容,取决于哪个 import 在前。两者都要的话,请从 两个不同的模块 import 同一个资源,或者直接遍历
Bun.embeddedFiles。
全栈可执行文件#
--compile 也能打包前端资源。import 你的 HTML,Bun 会把它连同引用到的 CSS 和 JS 一起内嵌:
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 myappbash我们实际跑了一遍 —— 服务正常启动,分配到端口,并以正确的 MIME 类型和缓存头提供内嵌的前端。一个文件,同时包含服务端和客户端,可以部署到任何地方。
你的 CLI 也可以”化身”成 Bun#
从 Bun 1.2.16 起,可执行文件可以回退到完整的 Bun CLI:
BUN_BE_BUN=1 ./myapp installbash我们验证过:一个由打印 "you should not see this" 的脚本编译出的二进制,正常运行时输出的正是这句话;而设置 BUN_BE_BUN=1 后,它会打印真实的 Bun 版本。这样你就能分发一个既能装包、又能打包依赖、还能运行其他文件的 CLI,而不必再多带一个二进制。
那 npm 依赖怎么办?#
它们被一起打包了。我们编译了一个 import picocolors 的脚本,然后把 node_modules 挪到别处,再运行二进制:
colored: hello-from-a-npm-packagetext照样正常工作。目标机器上什么都不需要 —— 连依赖目录都不需要。
什么时候不该编译#
编译不是免费的,也并非任何时候都是正确答案:
实践中的提醒:
- macOS Gatekeeper。 从网上下载的未签名二进制会被隔离并拦截,直到用户手动批准。要么分发已签名的二进制,要么告诉用户如何放行。
- Docker 镜像。 把 67 MB 的二进制复制进每一层镜像会让镜像膨胀。一个精简的 runtime 基础镜像往往更划算。
- 原生插件。 为你的构建机器编译的
.node插件本身仍是编译产物;交叉编译不会交叉编译原生 C++ 插件。这正是--target构建最好留在 CI 上、并在目标架构上执行的主要原因。 - 频繁更新。 每次发版都分发一个 67 MB 的文件,比往 npm 发布一个小包慢得多。
Bun.build() API#
上面的一切也能用编程方式完成 —— 这正是写构建脚本时想要的:
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#
# 一个文件,到处都能跑
bun build --compile ./cli.ts --outfile mycli
# 在笔记本上交叉编译
bun build --compile --target=bun-linux-arm64 ./cli.ts --outfile mycli
# 我们实际分发的配置
bun build --compile --minify --sourcemap=linked ./cli.ts --outfile myclibash- macOS arm64 上的产物是 67.6 MB —— 那是 Bun runtime,不是你的代码。
--minify不会让它变小。 - 启动收益随代码量增长:单文件脚本约 0.8 ms,400 模块的应用是 6.1 ms(39%)。
- 编译后的二进制里
import.meta.path是/$bunfs/root/<name>。真实路径请用process.execPath。 with { type: "file" }给你路径;with { type: "text" }给你内容。- 不要把同一个资源 import 两次 —— 第一个 import 的 attribute 胜出,并同时作用于两个变量。
- 入口文件用了顶层
await就别开--bytecode—— 在 Bun 1.4.3 上它构建不过。 - 一定带上
--sourcemap;否则堆栈会指向/$bunfs/root而不是你的源码。