1.1 Bun 是什么
Bun 是一个用 Zig 编写、包含在单个二进制里的一体化 JavaScript 工具链。它同时是:
- JavaScript 运行时
- 跑 .js / .ts / .jsx / .tsx 文件。底层用 Apple Safari 的 JavaScriptCore(JSC)引擎,而非 Node 用的 V8。
- 包管理器
bun install速度是 npm 的 25 倍,完全兼容 npm registry 和 package.json。- 打包器(Bundler)
bun build像 esbuild/Vite 一样把源码打包,支持多目标(browser/node/bun)。- 测试跑者
bun test是 Jest API 兼容的测试框架,内置 mock / snapshot / coverage。- 脚本执行器
bun run script-name跑 package.json 里的脚本,比npm run启动快 150 倍。
为什么用 Zig?
Zig 是一门系统编程语言(类似 Rust 的定位),但没有 GC、没有运行时、能无缝调用 C API。Bun 作者 Jarred Sumner 选择 Zig 是为了极致性能 + 小体积:Bun 的二进制只有 ~50MB,冷启动 <10ms。
1.2 Bun vs Node vs Deno
| 维度 | Node.js | Deno | Bun |
|---|---|---|---|
| 首发 | 2009 | 2020 | 2022 |
| 语言 | C++ | Rust | Zig |
| JS 引擎 | V8 | V8 | JavaScriptCore |
| TypeScript | 需 tsx/ts-node | 原生支持 | 原生支持 |
| 包管理 | npm/yarn/pnpm(外部) | URL 导入 / jsr | bun install(内置) |
| 测试 | node:test(较新) | Deno.test | bun test(Jest 兼容) |
| 打包 | 需 webpack/Vite 等 | 内置 deno bundle | 内置 bun build |
| Web 标准 API | 逐步补齐 | 严格 Web 标准 | Web 标准 + Node 兼容 |
| npm 兼容 | 原生 | 较新才支持 | 100% |
Bun 的定位
Deno 选"重来过"——抛弃 npm 生态、强制 Web 标准;Bun 选"兼容且更快"——npm 生态无缝、API 既实现 Node 也实现 Web 标准。这让 Bun 能直接跑大部分现存 Node 项目,迁移成本几乎为零。
1.3 JSCore vs V8
为什么 Bun 不用 V8?JSCore 的优势:
- 冷启动更快——Safari 团队把 JSCore 优化成"冷启动极快",适合短脚本场景。
- 内存占用更低——比 V8 少 30-50%。
- 更适合嵌入——API 比 V8 干净,Zig 调用开销小。
代价:某些长期运行后稳态性能 V8 略胜;且部分 V8 特定的 C++ 原生模块(node-gyp)在 Bun 下需要适配层。
1.4 安装 Bun
macOS / Linux / WSL:curl 一条命令
$ curl -fsSL https://bun.sh/install | bash
装好会往 ~/.bun/bin/bun 放二进制,自动改 shell profile 加 PATH。
macOS:Homebrew
$ brew install oven-sh/bun/bun
通过 npm 装(全平台)
$ npm install -g bun
Windows(原生支持从 1.1 起 GA)
> powershell -c "irm bun.sh/install.ps1 | iex"
验证
$ bun --version
# 1.2.x
$ bun --help
1.5 升级与卸载
$ bun upgrade # 升级到最新 stable
$ bun upgrade --canary # 升级到最新 canary(开发版)
$ rm -rf ~/.bun # 卸载(macOS/Linux)
1.6 第一次运行:hello world
// hello.ts
const name: string = "world";
console.log(`Hello, ${name}!`);
$ bun hello.ts
Hello, world!
注意:直接 bun hello.ts 就行——不需要 ts-node、不需要编译,Bun 原生懂 TypeScript。
1.7 直接跑 JSX/TSX
// greet.tsx
const el = <div>Hello <span>Bun</span></div>;
console.log(JSON.stringify(el));
$ bun greet.tsx
Bun 默认把 JSX 当 React.createElement,可在 bunfig.toml 里改 JSX 运行时。
1.8 初始化新项目
$ bun init # 交互式,和 npm init 类似但多问 JSX/TS 选项
$ bun init -y # 直接用默认
生成的文件:
my-app/
├── package.json
├── tsconfig.json # 预设 Bun 类型
├── bunfig.toml # Bun 专属配置(可选)
├── index.ts
├── .gitignore
└── README.md
1.9 bunfig.toml
Bun 自己的配置文件,放项目根。常用条目:
# bunfig.toml
[install]
registry = "https://registry.npmmirror.com"
# 私服示例
# registry = { url = "https://npm.company.com", token = "xxx" }
[install.scopes]
"@my-org" = { url = "https://npm.company.com", token = "$NPM_TOKEN" }
[test]
coverage = true
coverageThreshold = 0.8
用户级全局配置在 ~/.bunfig.toml,项目级覆盖。
1.10 小结
- Bun = 运行时 + 包管理 + 打包 + 测试 + 脚本执行,一个二进制搞定。
- 底层:Zig 语言 + JavaScriptCore 引擎,不同于 Node 的 C++/V8 组合。
- 安装:
curl bun.sh/install | bash,Windows 也 GA 了。 - 原生跑 .ts / .tsx / .jsx,不用 ts-node/tsx。
- 下一章深入
bun install——25 倍于 npm 的包管理体验。