Bun 运行时入门与生态概览:从安装到全栈实战

By | 2026年11月11日

为什么需要关注 Bun?

如果你已经厌倦了 Node.js 生态中工具链的碎片化——用 npm 装包、用 Jest 测试、用 esbuild 打包、用 nodemon 热重载——那么 Bun 的出现或许能让你眼前一亮。Bun 是一个一体化的 JavaScript 运行时,它底层基于 Zig 和 JavaScriptCore 引擎,号称启动速度比 Node.js 快 4 倍,同时内置了包管理器、测试运行器、打包器,甚至支持直接运行 TypeScript 和 JSX 文件。

本文不会重复官方文档的“Hello World”,而是通过一个完整的待办事项 API 项目,带你体验 Bun 在开发效率上的真实提升,并分享一些我在迁移过程中总结的踩坑经验。

环境准备与安装

Bun 支持 macOS、Linux 和 Windows(WSL 推荐)。安装方式很简单:


# macOS / Linux
curl -fsSL https://bun.sh/install | bash

# Windows (WSL)
curl -fsSL https://bun.sh/install | bash

安装完成后,验证版本:


bun --version
# 输出示例:1.1.0

💡 注意:Bun 的版本迭代很快,建议使用最新稳定版。如果你之前安装过旧版本,可以用 bun upgrade 升级。

初始化项目与依赖管理

Bun 内置了包管理器,命令与 npm 高度兼容。我们创建一个新目录并初始化:


mkdir bun-todo-api && cd bun-todo-api
bun init -y

这会生成 package.json 和 index.ts 入口文件。Bun 的 bun init 交互式脚手架会询问项目类型,选择“Blank”即可。

接下来安装依赖。我们将使用 Bun 原生的 HTTP 服务器和 SQLite 数据库(Bun 内置了 bun:sqlite 模块,无需额外安装驱动):


bun add zod

这里只安装了 zod 用于请求体验证,其他全部使用 Bun 内置能力。

编写一个 Todo API 服务

Bun 提供了 Bun.serve 来创建 HTTP 服务器,风格类似 Node.js 的 http 模块,但更简洁。我们来构建一个支持增删改查的 Todo API。

1. 数据库初始化

创建 db.ts,使用内置的 bun:sqlite:


import { Database } from "bun:sqlite";

const db = new Database("todos.sqlite", { create: true });

// 初始化表
db.run(`
  CREATE TABLE IF NOT EXISTS todos (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    completed INTEGER DEFAULT 0
  )
`);

export default db;

2. 定义数据模型与验证

创建 schema.ts,使用 zod 定义请求体结构:


import { z } from "zod";

export const TodoCreateSchema = z.object({
  title: z.string().min(1, "标题不能为空"),
  completed: z.boolean().optional().default(false),
});

export type TodoCreate = z.infer<typeof TodoCreateSchema>;

3. 实现 HTTP 服务器

创建 server.ts,编写路由和业务逻辑:


import { serve } from "bun";
import db from "./db";
import { TodoCreateSchema } from "./schema";

const server = serve({
  port: 3000,
  async fetch(req) {
    const url = new URL(req.url);
    const method = req.method;

    // 获取所有 todos
    if (url.pathname === "/todos" && method === "GET") {
      const todos = db.query("SELECT * FROM todos").all();
      return Response.json(todos);
    }

    // 创建 todo
    if (url.pathname === "/todos" && method === "POST") {
      try {
        const body = await req.json();
        const parsed = TodoCreateSchema.parse(body);
        const result = db.run(
          "INSERT INTO todos (title, completed) VALUES (?, ?)",
          [parsed.title, parsed.completed ? 1 : 0]
        );
        const newTodo = db.query("SELECT * FROM todos WHERE id = ?").get(result.lastInsertRowid);
        return Response.json(newTodo, { status: 201 });
      } catch (err) {
        if (err instanceof z.ZodError) {
          return Response.json({ error: err.errors }, { status: 400 });
        }
        return Response.json({ error: "Internal Server Error" }, { status: 500 });
      }
    }

    // 更新 todo(简化版:只更新 completed 状态)
    if (url.pathname.startsWith("/todos/") && method === "PATCH") {
      const id = parseInt(url.pathname.split("/")[2]);
      const body = await req.json();
      if (typeof body.completed !== "boolean") {
        return Response.json({ error: "completed 必须是布尔值" }, { status: 400 });
      }
      db.run("UPDATE todos SET completed = ? WHERE id = ?", [body.completed ? 1 : 0, id]);
      const updated = db.query("SELECT * FROM todos WHERE id = ?").get(id);
      if (!updated) {
        return Response.json({ error: "Todo 不存在" }, { status: 404 });
      }
      return Response.json(updated);
    }

    // 删除 todo
    if (url.pathname.startsWith("/todos/") && method === "DELETE") {
      const id = parseInt(url.pathname.split("/")[2]);
      const result = db.run("DELETE FROM todos WHERE id = ?", [id]);
      if (result.changes === 0) {
        return Response.json({ error: "Todo 不存在" }, { status: 404 });
      }
      return new Response(null, { status: 204 });
    }

    return new Response("Not Found", { status: 404 });
  },
});

console.log(`Server running at http://localhost:${server.port}`);

4. 运行与测试

直接运行 TypeScript 文件,无需编译:


bun run server.ts

用 curl 测试一下:


# 创建
curl -X POST http://localhost:3000/todos -H "Content-Type: application/json" -d '{"title":"学习 Bun"}'

# 获取列表
curl http://localhost:3000/todos

你会发现 Bun 启动几乎是瞬间完成的,而且直接运行 .ts 文件,省去了 ts-node 或 tsx 的配置。

使用 Bun 的测试运行器

Bun 内置了测试运行器,语法与 Jest 类似。我们为 API 写一个简单的测试。创建 server.test.ts:


import { describe, it, expect, beforeAll } from "bun:test";
import { serve } from "bun";
import db from "./db";

// 注意:为了测试,我们直接导入 server 模块会启动端口,这里改用动态导入或直接测试逻辑
// 更推荐将业务逻辑抽离为函数,这里为了简洁,我们直接测试数据库操作

describe("Todo 数据库操作", () => {
  beforeAll(() => {
    // 清空表
    db.run("DELETE FROM todos");
  });

  it("应该能插入并查询 todo", () => {
    const result = db.run("INSERT INTO todos (title) VALUES (?)", ["测试任务"]);
    const todo = db.query("SELECT * FROM todos WHERE id = ?").get(result.lastInsertRowid);
    expect(todo).toBeDefined();
    expect(todo.title).toBe("测试任务");
  });
});

运行测试:


bun test

Bun 的测试运行器速度极快,并且支持 TypeScript 和 JSX,无需额外配置。

💡 最佳实践:在实际项目中,建议将 HTTP 处理逻辑与服务器启动分离,例如导出一个 app 对象,便于测试时直接调用 fetch 方法,而不需要真正监听端口。

打包与部署

Bun 内置了打包器,可以将项目打包成单个文件。例如,打包 server.ts:


bun build ./server.ts --outdir ./dist --target bun

这会在 dist 目录生成 server.js,然后可以用 bun dist/server.js 运行。

对于生产环境,Bun 还支持编译为独立可执行文件(实验性):


bun build ./server.ts --compile --outfile todo-api

这会生成一个二进制文件 todo-api,可以在没有安装 Bun 的机器上运行(需要相同操作系统)。

常见坑与注意事项

  1. Node.js 兼容性:Bun 实现了大部分 Node.js API,但并非 100% 兼容。在使用某些原生模块(如 fs 的某些边缘功能)时,建议先测试。
  2. 包管理器锁文件:Bun 使用 bun.lockb 二进制锁文件,与 package-lock.json 不兼容。如果团队混合使用 npm 和 Bun,建议统一工具链。
  3. 环境变量:Bun 自动加载 .env 文件,无需 dotenv 包,但注意变量名不要与系统环境变量冲突。
  4. 热重载:使用 bun --watch server.ts 可以开启热重载,但生产环境不要使用。
  5. SQLite 的并发:bun:sqlite 是同步 API,在高并发场景下可能成为瓶颈。对于简单应用足够,但大型项目建议使用 PostgreSQL 等。

总结与下一步

通过这个实战项目,我们体验了 Bun 的几大核心优势:

  • 极速启动:直接运行 TypeScript,无需编译步骤。
  • 一体化工具链:包管理、测试、打包全部内置,减少配置成本。
  • 内置 SQLite:快速原型开发时非常方便。

Bun 的生态仍在快速发展中,目前已经支持 Next.js、Hono、Elysia 等流行框架。如果你正在启动一个新项目,尤其是 API 服务或 CLI 工具,Bun 值得一试。下一步可以探索:

  • 使用 Elysia 框架构建更结构化的 API。
  • 尝试 Bun 的 bun:ffi 调用原生库。
  • 关注 Bun 对 Node.js 兼容性的持续改进。

希望这篇教程能帮你快速上手 Bun,享受更流畅的开发体验。