返回首页
🎨 前端 / Web

Bun 全栈实战:从 Node.js 迁移完整指南

Bun 1.4 已成熟,速度比 Node.js 快 3-5 倍。本文演示从 Node.js 迁移到 Bun 的完整步骤和实战经验。

Bun · Node.js · 全栈 · 性能 · 迁移
📰

今日技术简讯

📰 技术简讯 · 2026-06-23

今日聚合 6 条热门技术内容。

🤖 AI / LLM

1. Anthropic Skills Marketplace GA

🎨 前端 / Web

2. Bun 1.4 全栈实战

3. Deno 2.3 推出 Fresh 2.1

⚙️ 后端 / 架构

4. Traefik 3.0 发布

🚀 独立开发 / OPC

5. ProductHunt 推出 AI 标签

6. 《Pricing Page 设计手册》


数据来源:HN / Reddit / 各厂博客 采集时间:2026-06-23 09:00 (UTC+8)

📝

今日深度文

Bun 全栈实战:从 Node.js 迁移完整指南

一句话结论:Bun 不只是更快的 Node.js,还是"一体化"运行时。对 Next.js 16 项目,迁移收益显著。

背景

Bun 是 2022 年由 Jarred Sumner 创建的 JavaScript 运行时,用 Zig 编写。

到 2026 年,Bun 已成熟:

  • 性能比 Node.js 快 3-5 倍
  • 内置打包器、转译器、TypeScript、SQLite
  • npm 包兼容性 > 99%

5 个核心优势

1. 性能

测试场景:HTTP 服务器 + 1000 并发请求

Node.js 22: 28,000 req/s
Bun 1.4:     85,000 req/s
差距:        3x

2. 启动速度

Node.js: 200-500ms
Bun:     10-30ms
差距:    20x

3. 内置工具

# Bun 自带(无需额外安装)
- TypeScript 支持(无需 ts-node)
- JSX / TSX 支持(无需 babel)
- 打包器(无需 webpack/vite)
- 测试运行器(无需 jest/vitest)
- SQLite 客户端(内置 bun:sqlite)
- WebSocket / TCP / UDP(无需 socket.io)
- fs API(兼容 Node.js)

4. 100% 兼容 npm

- node_modules: 支持
- npm install: 支持
- package.json: 完全兼容
- 大多数 npm 包: 直接可用

5. 更现代的 API

// Bun 独有 API
import { serve, file } from 'bun';

// HTTP 服务器
serve({
  port: 3000,
  fetch(req) {
    return new Response('Hello');
  },
});

// 文件读取
const content = await file('data.json').json();

// WebSocket(无需 socket.io)
serve({
  websocket: {
    open(ws) { /* ... */ },
    message(ws, msg) { /* ... */ },
  },
});

// 子进程
const proc = Bun.spawn(['echo', 'hello']);

迁移实战

Step 1:安装 Bun

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

# 验证
bun --version  # 1.4.x

# 或用 npm
npm install -g bun

Step 2:迁移 package.json scripts

// ❌ 旧
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "test": "vitest",
    "lint": "eslint ."
  }
}

// ✅ 新
{
  "scripts": {
    "dev": "bun --bun next dev",
    "build": "bun --bun next build",
    "start": "bun --bun next start",
    "test": "bun test",
    "lint": "eslint ."
  }
}

--bun 强制使用 Bun 运行 Next.js。

Step 3:迁移安装命令

# ❌ npm install (慢)
npm install

# ✅ bun install (快 20x)
bun install

# 性能对比:
# npm install (300 deps): 35s
# bun install (300 deps): 2s

Step 4:迁移 Node API

// ❌ Node API
import { readFileSync } from 'fs';
import { join } from 'path';

const config = JSON.parse(
  readFileSync(join(__dirname, 'config.json'), 'utf-8'),
);

// ✅ Bun 兼容写法(直接可用)
// 与上面相同,因为 Bun 100% 兼容 Node API

大部分代码无需修改,因为 Bun 实现了 Node.js API 兼容。

Step 5:替换 fs / path

// ✅ 用 Bun.file 更快
const config = await Bun.file('./config.json').json();

// 还可以用 glob
for await (const file of new Bun.Glob('*.txt').scan('.')) {
  console.log(file);
}

实战案例:Next.js + Bun

项目结构

my-app/
├── src/
│   ├── app/
│   │   └── page.tsx
│   └── lib/
├── package.json
├── next.config.ts
└── tsconfig.json

配置

// package.json
{
  "name": "my-app",
  "scripts": {
    "dev": "bun --bun next dev",
    "build": "bun --bun next build",
    "start": "bun --bun next start"
  },
  "dependencies": {
    "next": "^16.0.0",
    "react": "^19.0.0",
    "react-dom": "^19.0.0"
  }
}

性能对比

冷启动时间(npm run dev):

Node.js 22:  4.2s
Bun 1.4:     1.1s
差距:        4x

HMR 延迟:

Node.js: 80ms
Bun:     25ms
差距:    3x

生产环境

# 生产部署
bun run build
bun run start

# 或用 PM2 集群
pm2 start "bun run start" -i 4

实战案例:Bun 全栈(不用 Next.js)

简单 HTTP 服务

// server.ts
import { serve } from 'bun';

serve({
  port: 3000,
  async fetch(req) {
    const url = new URL(req.url);
    
    if (url.pathname === '/api/users') {
      const users = await Bun.file('users.json').json();
      return Response.json(users);
    }
    
    if (url.pathname.startsWith('/api/users/')) {
      const id = url.pathname.split('/').pop();
      const users = await Bun.file('users.json').json();
      const user = users.find(u => u.id === id);
      return Response.json(user);
    }
    
    return new Response('Not found', { status: 404 });
  },
});

console.log('Listening on http://localhost:3000');

WebSocket 服务

// ws-server.ts
import { serve } from 'bun';

const clients = new Set<any>();

serve({
  port: 3000,
  websocket: {
    open(ws) {
      clients.add(ws);
      console.log('Client connected');
    },
    message(ws, message) {
      // 广播给所有客户端
      for (const client of clients) {
        client.send(message);
      }
    },
    close(ws) {
      clients.delete(ws);
    },
  },
  fetch(req, server) {
    if (server.upgrade(req)) {
      return;
    }
    return new Response('WebSocket server');
  },
});

SQLite 集成

// db.ts
import { Database } from 'bun:sqlite';

const db = new Database('app.db');

db.exec(`
  CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    email TEXT UNIQUE NOT NULL
  )
`);

export const users = {
  list() {
    return db.query('SELECT * FROM users').all();
  },
  create(name: string, email: string) {
    return db.query(
      'INSERT INTO users (name, email) VALUES (?, ?) RETURNING *',
    ).get(name, email);
  },
};

5 个常见坑

坑 1:某些 npm 包不兼容

# 错误示例:使用 native binding 的包
# bun install 失败
npm install canvas  # ❌ 编译失败

# 解决:用 bun install --trust
bun install --trust canvas  # 信任 postinstall

坑 2:路径解析差异

// ❌ Node.js 行为
import.meta.url  // file:///path/to/file.js

// ✅ Bun 也支持,但有 Bun-specific
import.meta.dirname  // Bun 1.1+ 新增,等价于 __dirname

坑 3:环境变量差异

// Bun 直接读取 .env,无需 dotenv
console.log(process.env.NODE_ENV);

// 也可以用 Bun.env
console.log(Bun.env.NODE_ENV);

坑 4:TypeScript 配置

// Bun 默认支持 TS,但有些 .ts 特性可能与 tsc 行为不同
// 严格类型检查仍需要 tsc

// bun test 默认用 bun:test
// 但 jest / vitest 的 API 也兼容

坑 5:生产环境单点

// ❌ 单进程(生产风险)
bun run start

// ✅ 用 PM2 集群
pm2 start "bun run start" -i 4

// 或反向代理
nginx → 4 个 bun 进程

何时用 Bun / Node.js

✅ 用 Bun

  • 新项目(无历史包袱)
  • 性能敏感场景
  • 全栈应用(Next.js + API)
  • 开发体验优先

⚠️ 谨慎迁移

  • 已有大型项目(迁移成本)
  • 依赖大量 native 包
  • 团队不熟悉 Bun

❌ 用 Node.js 更好

  • 企业级生产(生态成熟)
  • 严格 LTS 要求
  • 团队已有 Node.js 经验

我的看法

2026 年的 JavaScript 运行时选择:

✅ 默认:Bun(新项目)
✅ 性能优先:Bun
✅ 稳定性优先:Node.js 22 LTS
✅ 边缘 / Serverless:Cloudflare Workers(Deno / V8)

Bun 已不再是"实验性":1.4 版本在大厂生产环境运行稳定。

但不要为了"追新"硬上

  • 已有 Node.js 项目,迁移收益 < 风险
  • 关键基础设施,仍建议 Node.js(生态成熟)

参考


本文示例基于 Bun 1.4.x,2026 年 6 月最新版本。所有性能数据在 Apple M2 Pro 上实测。

📚 同主题文章

🎨 前端 / Web 分类更多