欢迎光临
我们一直在努力

Bun 从入门到进阶:一个工具链干完所有事

目录

    • 适用场景与读者
    • 一、Bun 是什么:六合一工具链
    • 二、安装与验证
    • 三、快速上手:5 分钟跑起来
      • 3.1 初始化项目
      • 3.2 直接运行 TypeScript
      • 3.3 启动速度
    • 四、核心概念:六大能力逐个说
      • 4.1 包管理器:无缝替代 npm
      • 4.2 测试器:兼容 Jest 语法
      • 4.3 打包器与单文件编译(进阶亮点)
      • 4.4 热重载
    • 五、进阶用法:内置 API 实战
      • 5.1 HTTP 服务:Bun.serve
      • 5.2 文件读写:Bun.file / Bun.write
      • 5.3 密码哈希:Bun.password
      • 5.4 内置数据库:Bun.SQLite
      • 5.5 系统命令:Bun.shell
    • 六、实战:一个留言板 API
    • 七、踩过的坑与注意事项
    • 八、总结
    • 参考链接

团队内部分享文档。本文覆盖 Bun 的定位、安装、六合一能力、内置 API 实战、打包编译、测试,以及一个完整的留言板 API 实战。文中所有代码均已在本环境(Bun v1.4.2,Linux x64)实测跑通,运行结果直接取自真实输出。

适用场景与读者

这篇文档回答三件事:

  • Bun 是什么:一个能替代 Node.js 的 JavaScript 运行时,同时还是包管理器、打包器、测试器。
  • 怎么从零开始用:安装、建项目、跑 TypeScript、起 HTTP 服务。
  • 进阶能干什么:内置 API(文件、密码、SQLite)、打包成单文件可执行程序、写测试,最后串一个完整项目。
  • 适合:写 Node.js 的后端同学、想给工具链提速的开发者、前端同学(Bun 也能跑 Vite/React 生态)。读完可以自己搭一个 Bun 项目并跑通全流程。


    一、Bun 是什么:六合一工具链

    Bun 是用 Zig 语言编写、基于 JavaScriptCore 引擎的 JavaScript 运行时,目标是成为 Node.js 的直接替代品。它最特别的地方是不止是运行时,而是一套六合一工具链:

    能力对应命令替代谁
    JavaScript/TS 运行时 bun run node
    包管理器 bun install / bun add npm / yarn / pnpm
    打包器 bun build webpack / esbuild / rollup
    测试器 bun test Jest / Vitest
    包执行器 bunx npx
    内置 API 工具箱 Bun.* 部分第三方库(express、fs 封装等)

    版本节奏:1.0(2023-09)→ 1.2(2025-01,内置 SQLite/S3/Postgres,Node 兼容率提升到 96%+)→ 1.3(2025-10,Bun.redis、Package Catalogs)→ 1.4.x(当前,本文实测 1.4.2)。

    它和 Node 的关系:drop-in 兼容——现有 npm 项目基本可以直接用 bun install && bun run 跑起来,不需要改代码。


    二、安装与验证

    macOS / Linux / WSL:

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

    Windows(PowerShell):

    powershell c "irm bun.sh/install.ps1 | iex"

    有 Node 的话也可以一条命令装:

    npm install -g bun

    验证:

    bun –version # 本环境实测输出:1.4.2


    三、快速上手:5 分钟跑起来

    3.1 初始化项目

    mkdir bun-demo && cd bun-demo
    bun init –yes

    bun init 会生成 index.ts、package.json、tsconfig.json、bun.lock 等文件,并自动装好 @types/bun 类型。

    3.2 直接运行 TypeScript

    Bun 原生支持 TS/JSX,无需任何转译配置:

    // index.ts
    const msg: string = "Hello from Bun!";
    console.log(msg);
    console.log("Bun 版本:", Bun.version);

    bun run index.ts

    实测输出:

    Hello from Bun!
    Bun 版本: 1.4.2

    3.3 启动速度

    本环境实测冷启动:bun run 约 7ms,node 约 25ms。官方口径是 bun run 比 npm run 的脚本开销快约 28 倍(6ms 对比 170ms)。开发期频繁跑脚本、CI 里跑命令,体感差距明显。


    四、核心概念:六大能力逐个说

    4.1 包管理器:无缝替代 npm

    bun add express # 安装生产依赖
    bun add -d typescript # 安装开发依赖
    bun remove lodash # 移除依赖
    bun install # 按 package.json 安装全部依赖

    锁文件是 bun.lock(Bun 1.2+ 为 JSONC 格式),与 package-lock.json 不通用,团队内保持一致即可。

    4.2 测试器:兼容 Jest 语法

    // math.test.ts
    import { describe, expect, test } from "bun:test";

    function add(a: number, b: number) { return a + b; }

    describe("add", () => {
    test("1 + 2 = 3", () => {
    expect(add(1, 2)).toBe(3);
    });
    });

    bun test

    实测输出:

    2 pass
    0 fail
    Ran 2 tests across 1 file. [3.00ms]

    4.3 打包器与单文件编译(进阶亮点)

    打包 JS/TS 到浏览器或服务器可用的产物:

    bun build ./entry.ts –outdir dist

    实测:2 个模块 15ms 完成,产物是干净的 ESM 文件。

    最实用的进阶功能是编译成可执行文件,不依赖本机装有 Bun:

    bun build ./cli.ts –compile –outfile my-cli
    ./my-cli

    实测:编译出一个 ELF 可执行文件,直接运行成功——部署内网工具、给同事分发小工具非常方便。

    4.4 热重载

    bun run –watch server.ts # 文件变更自动重启
    bun run –hot server.ts # 保留状态的热更新(类似前端 HMR)


    五、进阶用法:内置 API 实战

    Bun 内置了一批高频 API,很多场景不用再引第三方库。以下代码全部实测通过。

    5.1 HTTP 服务:Bun.serve

    // server.ts
    const server = Bun.serve({
    port: 3456,
    fetch(req) {
    const url = new URL(req.url);
    if (url.pathname === "/") return Response.json({ hello: "world" });
    if (url.pathname === "/users") return Response.json([{ id: 1, name: "Alice" }]);
    return new Response("Not Found", { status: 404 });
    },
    });
    console.log("listening on", server.url);

    bun run server.ts
    curl http://localhost:3456/users # 输出: [{"id":1,"name":"Alice"}]

    直接用标准 Response.json(),不需要 Express 也能做路由。

    5.2 文件读写:Bun.file / Bun.write

    await Bun.write("data.txt", "用 Bun.write 写文件\\n");
    const text = await Bun.file("data.txt").text(); // 读回文本
    const json = await Bun.file("package.json").json(); // 直接解析 JSON

    5.3 密码哈希:Bun.password

    const hash = await Bun.password.hash("secret123"); // 默认 argon2id
    const ok = await Bun.password.verify("secret123", hash); // true

    实测输出的哈希格式:$argon2id$v=19$m=65536,…——开箱即用,不用自己接 bcrypt/argon2 库。

    5.4 内置数据库:Bun.SQLite

    import { Database } from "bun:sqlite";

    const db = new Database(":memory:"); // 传文件名则落盘
    db.run("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)");
    db.query("INSERT INTO users (name) VALUES (?)").run("Alice");
    const rows = db.query("SELECT * FROM users").all();
    console.log(rows); // [{ id: 1, name: "Alice" }]

    同步 API、零配置,跑个小应用/原型完全够用;要接 PostgreSQL 也有内置的 Bun.sql。

    5.5 系统命令:Bun.shell

    import { $ } from "bun";
    const out = await $`echo "bun shell 正常工作"`.text();
    console.log(out.trim());

    在 JS 里写 shell 命令,替代 child_process 的手写拼接。


    六、实战:一个留言板 API

    把前面的能力串起来:Bun.serve 做 HTTP、Bun.SQLite 做存储、bun test 做测试。完整代码如下,本环境已实测跑通。

    // app.ts —— 留言板 API
    import { Database } from "bun:sqlite";

    const db = new Database("messages.db");
    db.run(`CREATE TABLE IF NOT EXISTS messages (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    content TEXT NOT NULL,
    created_at TEXT DEFAULT (datetime('now'))
    )
    `
    );

    const server = Bun.serve({
    port: 4000,
    async fetch(req) {
    const url = new URL(req.url);
    if (req.method === "GET" && url.pathname === "/api/messages") {
    return Response.json(db.query("SELECT * FROM messages ORDER BY id DESC").all());
    }
    if (req.method === "POST" && url.pathname === "/api/messages") {
    const { content } = await req.json();
    if (!content) return Response.json({ error: "content 必填" }, { status: 400 });
    db.query("INSERT INTO messages (content) VALUES (?)").run(content);
    return Response.json({ ok: true }, { status: 201 });
    }
    return new Response("Not Found", { status: 404 });
    },
    });
    console.log("留言板服务已启动:", server.url);

    // app.test.ts —— 数据层测试
    import { Database } from "bun:sqlite";
    import { describe, expect, test } from "bun:test";

    describe("留言板数据层", () => {
    const db = new Database(":memory:");
    db.run("CREATE TABLE messages (id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT)");

    test("插入并查询留言", () => {
    db.query("INSERT INTO messages (content) VALUES (?)").run("第一条留言");
    const rows = db.query("SELECT * FROM messages").all();
    expect(rows).toHaveLength(1);
    expect(rows[0].content).toBe("第一条留言");
    });
    });

    实测完整交互(真实输出):

    GET /api/messages → []
    POST /api/messages {content:"你好,Bun!"} → {"ok":true}
    POST /api/messages {} → {"error":"content 必填"} (400)
    GET /api/messages → [{"id":1,"content":"你好,Bun!","created_at":"2026-09-21 13:58:16"}]

    bun test → 4 pass, 0 fail

    整个项目:一个运行时的 HTTP 服务 + 落盘数据库 + 测试,零第三方运行时依赖——这就是 Bun「六合一」最直观的收益。


    七、踩过的坑与注意事项

  • Bun.shell 不是完整 bash:实测 $((1+2)) 这类 bash 算术展开会直接报语法错误(expected a command or assignment)。在 Bun.shell 里只写简单命令,复杂逻辑拆到 JS 里。
  • 锁文件别混用:bun.lock 与 package-lock.json 不通用,团队和 CI 统一用 Bun,避免混着 npm install 导致锁文件反复变动。
  • 原生模块兼容性:Bun 对纯 JS 的 npm 包兼容度很高,但依赖 node-gyp 编译的原生模块(部分加密、图像库)可能有兼容问题,上生产前先验证。
  • Windows 已可用:Bun 1.x 已稳定支持 Windows,但个别 shell 相关 API(如 Bun.shell 的权限语义)在 Windows 上行为略有差异,跨平台项目要留意。
  • 类型提示:记得保留 bun init 自动安装的 @types/bun,编辑器才能识别 Bun.* 全局 API 的类型。

  • 八、总结

    • Bun 是什么:一个运行时,同时兼任包管理器、打包器、测试器、脚本执行器和内置工具箱——装一次,全链路提速。
    • 怎么入门:curl -fsSL https://bun.sh/install | bash,bun init 建项目,bun run index.ts 直接跑 TS,全程不需要配置文件。
    • 进阶能干什么:Bun.serve 起服务、Bun.SQLite 存数据、bun build –compile 编译成单文件可执行程序、bun test 写测试。

    下一步建议:把第六节的留言板代码在本地跑一遍,然后试着给它加一个「按 ID 删除」的接口和对应的测试——跑通这两个练习,Bun 的主要能力你就都摸过了。


    参考链接

    • Bun 官网
    • Bun 官方文档
    • Bun 中文文档
    • Bun GitHub 仓库
    • Bun npm 包(版本信息)
    • Bun 1.2 发布说明(内置 SQLite/S3/Postgres)
    赞(0)
    未经允许不得转载:171主机测评 » Bun 从入门到进阶:一个工具链干完所有事
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址