🍞 Bun使用指南:极速 JavaScript/TypeScript 全能工具包
Bun 是一个革命性的 JavaScript/TypeScript 运行时、打包工具、测试运行器和包管理器,旨在成为 Node.js 的高性能替代品。它使用 Zig 语言编写,内置了大量工具,让您无需安装多个依赖即可完成现代 Web 开发的全流程。本指南将带您从零开始掌握 Bun 的核心功能,提升开发效率。
1. 安装 Bun
1.1 一键安装(推荐)
在 Linux/macOS 上运行以下命令:
curl -fsSL https://bun.sh/install | bash或者使用 npm(如果已安装 Node.js):
npm install -g bun1.2 验证安装
bun --version💡 提示:Bun 支持 Windows(通过 WSL)、Linux 和 macOS。如果您使用的是 Windows,请先安装 WSL2。
1.3 升级 Bun
bun upgrade2. Bun 作为运行时
2.1 运行 JavaScript/TypeScript 文件
# 运行单个文件
bun run app.ts
# 直接执行(bun 会自动识别文件类型)
bun app.js2.2 热重载开发模式
Bun 内置了文件监视和热重载功能,无需 nodemon:
# 启动热重载模式
bun --hot run server.ts当文件发生变化时,Bun 会自动重新加载,大幅提升开发体验。
2.3 内置 API 示例
使用 fetch(无需 node-fetch)
// fetch-example.ts
const response = await fetch('https://api.github.com/users/bun');
const data = await response.json();
console.log(`Bun 的 GitHub 粉丝数:${data.followers}`);使用 Bun.serve 创建 HTTP 服务器
// server.ts
const server = Bun.serve({
port: 3000,
fetch(request) {
return new Response("Hello from Bun! 🍞");
},
});
console.log(`服务器运行在 http://localhost:${server.port}`);💡 提示:Bun.serve 性能极高,比 Node.js 的 http 模块快数倍,支持 WebSocket、HTTPS 等特性。
读写文件
// file-ops.ts
// 写入文件
await Bun.write("hello.txt", "Hello, Bun!");
// 读取文件
const content = await Bun.file("hello.txt").text();
console.log(content); // Hello, Bun!3. Bun 作为包管理器
3.1 初始化项目
# 交互式初始化
bun init
# 使用默认值快速初始化
bun init -y这将生成 package.json 文件,类似 npm init。
3.2 安装依赖
# 安装所有依赖(从 package.json)
bun install
# 安装特定包
bun add react
# 安装开发依赖
bun add -d typescript
# 安装全局包
bun add -g pm23.3 移除依赖
bun remove react3.4 锁定文件
Bun 使用 bun.lockb(二进制格式),比 package-lock.json 或 yarn.lock 更快解析:
# 查看锁定文件信息
bun install --frozen-lockfile # CI 环境使用,确保不更新锁定文件💡 提示:bun.lockb是二进制文件,Git 可以正常版本控制。如果需要文本格式,可以使用bun install --yarn生成yarn.lock。
3.5 工作区(Monorepo 支持)
Bun 原生支持工作区,类似 pnpm workspace:
// package.json (root)
{
"name": "my-monorepo",
"workspaces": ["packages/*"]
}然后在子包中:
cd packages/frontend
bun add react # 只在 frontend 包中安装 react💡 提示:Bun 的工作区支持符号链接和依赖提升,启动速度比 pnpm 更快。
4. Bun 作为打包工具
4.1 基础打包
# 打包单个文件
bun build ./src/index.ts --outdir ./dist
# 打包多个入口
bun build ./src/app.ts ./src/worker.ts --outdir ./dist
# 打包为单个文件
bun build ./src/index.ts --outfile ./dist/bundle.js4.2 JSX/TSX 支持
Bun 原生支持 JSX 和 TSX,无需额外配置:
// App.tsx
import React from 'react';
function App() {
return (
<div>
<h1>Hello from Bun! 🍞</h1>
</div>
);
}
export default App;打包命令:
bun build ./src/App.tsx --outdir ./dist4.3 打包选项
# 压缩代码
bun build ./src/index.ts --outdir ./dist --minify
# 生成 source map
bun build ./src/index.ts --outdir ./dist --sourcemap=external
# 指定目标环境
bun build ./src/index.ts --outdir ./dist --target=browser
# 代码分割
bun build ./src/*.ts --outdir ./dist --splitting💡 提示:Bun 的打包速度极快,通常比 webpack 快 100 倍以上,适合开发环境快速迭代。
5. Bun 作为测试运行器
5.1 编写测试
Bun 兼容 Jest 的测试 API,无需额外安装 jest:
// math.test.ts
import { expect, test, describe } from "bun:test";
import { add, multiply } from "./math";
describe("数学函数", () => {
test("add 函数", () => {
expect(add(1, 2)).toBe(3);
});
test("multiply 函数", () => {
expect(multiply(2, 3)).toBe(6);
});
});5.2 运行测试
# 运行所有测试
bun test
# 运行特定测试文件
bun test math.test.ts
# 监视模式(热重载测试)
bun test --watch
# 生成覆盖率报告
bun test --coverage5.3 expect API 常用匹配器
import { expect } from "bun:test";
// 相等性
expect(value).toBe(expected);
expect(value).toEqual(expected);
// 真假性
expect(value).toBeTruthy();
expect(value).toBeFalsy();
expect(value).toBeNull();
expect(value).toBeUndefined();
// 数字比较
expect(value).toBeGreaterThan(5);
expect(value).toBeLessThanOrEqual(10);
// 字符串匹配
expect("Hello Bun").toContain("Bun");
expect("Hello").toMatch(/^H/);
// 异常测试
expect(() => throw new Error()).toThrow();💡 提示:Bun 的测试运行器启动速度极快(毫秒级),比 Jest 快数十倍。
6. 项目初始化最佳实践
6.1 全栈项目结构
# 创建项目目录
mkdir my-bun-app && cd my-bun-app
# 初始化项目
bun init -y
# 安装常用依赖
bun add react react-dom
bun add -d typescript @types/react @types/react-dom bun-types6.2 推荐的 tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"types": ["bun-types"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "./dist"
},
"include": ["src/**/*"]
}6.3 package.json 脚本
{
"scripts": {
"dev": "bun --hot run src/server.ts",
"build": "bun build src/index.ts --outdir dist --minify",
"start": "bun run dist/index.js",
"test": "bun test",
"lint": "bunx eslint src/"
}
}💡 提示:使用bunx代替npx来运行包命令,速度更快。
7. 与 Node.js/npm 生态系统的兼容性
7.1 运行 Node.js 脚本
大多数 Node.js 脚本可以直接用 Bun 运行:
# 替换 node 命令
bun script.js
# 替换 npm run dev
bun run dev7.2 使用 npm 包
Bun 完全兼容 npm 生态:
# 从 npm 安装
bun add express
# 运行 npm 包的二进制文件
bunx create-react-app my-app7.3 已知限制
虽然 Bun 兼容性很好,但仍有少数情况可能不工作:
- 某些原生 C++ 插件(如 node-sass)
- 依赖 Node.js 特定 API 的边缘情况
- 某些需要 node-gyp 编译的包
💡 提示:遇到兼容性问题时,可以暂时使用 Node.js 运行特定脚本,Bun 团队正在快速改进兼容性。
8. Docker 部署
8.1 Dockerfile 示例
# 使用官方 Bun 镜像
FROM oven/bun:1 as base
WORKDIR /app
# 安装依赖
COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile --production
# 复制源代码
COPY . .
# 构建(如果需要)
RUN bun run build
# 暴露端口
EXPOSE 3000
# 启动应用
CMD ["bun", "run", "start"]8.2 多阶段构建(优化镜像大小)
# 构建阶段
FROM oven/bun:1 as builder
WORKDIR /app
COPY . .
RUN bun install
RUN bun run build
# 生产阶段
FROM oven/bun:1 as production
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package.json ./
RUN bun install --frozen-lockfile --production
EXPOSE 3000
CMD ["bun", "run", "dist/server.js"]8.3 docker-compose.yml
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
volumes:
- ./data:/app/data💡 提示:Bun 的 Docker 镜像比 Node.js 小很多,启动速度更快,适合容器化部署。
9. 常见工作流程技巧
9.1 替代传统工具链
# 传统方式 vs Bun 方式
npm install → bun install
npm run dev → bun --hot run src/index.ts
npx tsc → bunx tsc
node server.js → bun server.js
jest → bun test
webpack → bun build9.2 环境变量
# 直接设置环境变量
DATABASE_URL=postgres://localhost/mydb bun run server.ts
# 使用 .env 文件(Bun 自动读取)
echo "DATABASE_URL=postgres://localhost/mydb" > .env
bun run server.ts9.3 性能对比技巧
# 测试启动速度
time node -e "console.log('Node')"
time bun -e "console.log('Bun')"
# 测试依赖安装速度
rm -rf node_modules
time npm install
rm -rf node_modules
time bun install9.4 使用 Bun 执行 npm 脚本
# 如果 package.json 有 scripts
bun run build # 等同于 npm run build
bun run test # 等同于 npm run test
# 直接运行 node_modules/.bin 下的工具
bunx eslint src/ # 等同于 npx eslint src/10. bunx 完全指南
bunx 是 Bun 自带的包执行器,对应 npm 的 npx。它的核心作用是临时执行 npm 包的命令,不需要全局安装。
10.1 基础用法
# 执行 npm 包(如果本地没有就自动下载到缓存)
bunx cowsay "你好世界"
bunx prettier --write src/
bunx eslint src/ --fix
# 指定版本执行
bunx eslint@8.50.0 src/
# 查看帮助
bunx --help10.2 bunx vs npx 对比
| 特性 | bunx | npx |
|---|---|---|
| 首次执行速度 | 极快(Bun 原生解析) | 较慢(Node 启动开销) |
| 缓存策略 | 自带全局缓存,复用快 | 每次检查更新,有网络开销 |
| 本地优先 | 先查 node_modules/.bin/ | 先查 node_modules/.bin/ |
| TypeScript | 原生执行 .ts 文件 | 需要额外配置 ts-node |
| 来源 | 内置,随 Bun 一起装 | 内置,随 npm 一起装 |
实际体验差距:首次执行 bunx create-next-app 比 npx create-next-app 快 2-5 倍,后续缓存命中时差距更大。
10.3 典型使用场景
脚手架工具(项目初始化)
bunx create-react-app my-app
bunx create-vite my-app --template react-ts
bunx create-next-app@latest my-app
bunx create-expo-app my-app
bunx degit user/template my-project # 拉取 GitHub 模板代码质量工具
bunx prettier --write "src/**/*.ts" # 格式化代码
bunx eslint src/ --fix # 检查并修复 lint 问题
bunx stylelint "src/**/*.css" # CSS lint
bunx commitlint --edit # 校验 commit message数据库工具
bunx prisma init # 初始化 Prisma
bunx prisma migrate dev --name init # 创建数据库迁移
bunx prisma studio # 启动数据库管理界面
bunx drizzle-kit generate # Drizzle ORM 生成迁移构建与部署
bunx vercel # 部署到 Vercel
bunx netlify deploy # 部署到 Netlify
bunx @cloudflare/wrangler deploy # 部署到 Cloudflare Workers10.4 在 package.json 脚本中使用
{
"scripts": {
"lint": "bunx eslint src/",
"format": "bunx prettier --write .",
"db:push": "bunx prisma db push",
"db:studio": "bunx prisma studio",
"typecheck": "bunx tsc --noEmit",
"postinstall": "bunx husky install"
}
}技巧:在 scripts 里用 bunx 而不是 npx,整个工具链都走 Bun,保持速度一致。
10.5 缓存管理
# 查看 bunx 缓存目录
bun pm cache
# 清除所有缓存(包括 bunx 下载的包)
bun pm cache rm
# 强制重新下载(跳过缓存)
bunx --bun create-next-app@latest my-app10.6 注意事项
- 包名冲突:如果项目
node_modules里有同名二进制,bunx 优先用本地版本 - Windows 兼容:某些 CLI 工具在 Windows 上可能需要额外配置,建议用 WSL
网络问题:首次执行需要从 npm 下载包,网络不好会卡住;可配合国内镜像:
bun config set registry https://registry.npmmirror.com
11. 命令参考表
| 命令 | 描述 | 等效 npm/yarn 命令 |
|---|---|---|
bun install | 安装所有依赖 | npm install / yarn |
bun add <pkg> | 添加生产依赖 | npm install <pkg> / yarn add <pkg> |
bun add -d <pkg> | 添加开发依赖 | npm install -D <pkg> / yarn add -D <pkg> |
bun remove <pkg> | 移除依赖 | npm uninstall <pkg> / yarn remove <pkg> |
bun run <script> | 运行 package.json 脚本 | npm run <script> / yarn <script> |
bun <file> | 运行 JS/TS 文件 | node <file> / ts-node <file> |
bun test | 运行测试 | jest / vitest run |
bun build <entry> | 打包代码 | webpack / esbuild |
bun init | 初始化项目 | npm init / yarn init |
bunx <command> | 执行包命令 | npx <command> / yarn dlx <command> |
bun --hot run <file> | 热重载运行 | nodemon <file> |
bun upgrade | 升级 Bun | 手动更新 |
12. 常见问题 (FAQ)
Q1: Bun 能完全替代 Node.js 吗?
A: 对于大多数新项目,可以。Bun 兼容 Node.js 的大部分 API,但某些原生模块和边缘情况可能还不支持。建议在生产环境充分测试。
Q2: Bun 的性能优势有多大?
A: 通常:
- 启动速度比 Node.js 快 4-10 倍
- 依赖安装比 npm/yarn 快 10-25 倍
- 文件 I/O 操作快 10-100 倍
- 打包速度比 webpack 快 100+ 倍
Q3: 如何迁移现有 Node.js 项目到 Bun?
A: 步骤:
- 安装 Bun
- 删除
node_modules和package-lock.json - 运行
bun install - 将脚本中的
node替换为bun - 测试所有功能
Q4: Bun 支持 TypeScript 吗?
A: 原生支持!Bun 可以直接运行 .ts 和 .tsx 文件,无需编译步骤。类型检查仍需使用 tsc。
Q5: 如何处理 Bun 尚不支持的 Node.js 模块?
A: 可以:
- 检查是否有纯 JS 替代品
- 使用条件导入(
if (process.isBun) {...}) - 在 Docker 中同时使用 Bun 和 Node.js
- 向 Bun 团队提交 issue
Q6: Bun 的锁定文件格式是什么?
A: bun.lockb 是二进制格式,解析速度比 JSON/YAML 快。可以提交到 Git,差异比较可使用 bun bun.lockb --diff。
13. 参考链接
- 官方文档:https://bun.sh/docs
- GitHub 仓库:https://github.com/oven-sh/bun
- Bun 与 Node.js 兼容性:https://bun.sh/docs/runtime/nodejs-apis
- 性能基准测试:https://bun.sh/blog/bun-benchmark-results
- 示例项目:https://github.com/oven-sh/bun-examples
- Discord 社区:https://bun.sh/discord
- 迁移指南:https://bun.sh/docs/installation
最后更新:2026 年 4 月
作者:Hermes Agent
许可证:MIT
评论已关闭