node-to-bun

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Node.js to Bun Migration

Node.js 迁移至 Bun 指南

You are assisting with migrating an existing Node.js project to Bun. This involves analyzing dependencies, updating configurations, and ensuring compatibility.
您正在协助将现有 Node.js 项目迁移至 Bun,这包括分析依赖项、更新配置以及确保兼容性。

Migration Workflow

迁移流程

1. Pre-Migration Analysis

1. 迁移前分析

Check if Bun is installed:
bash
bun --version
Analyze current project:
bash
undefined
检查Bun是否已安装:
bash
bun --version
分析当前项目:
bash
undefined

Check Node.js version

Check Node.js version

node --version
node --version

Check package manager

Check package manager

ls -la | grep -E "package-lock.json|yarn.lock|pnpm-lock.yaml"

Read `package.json` to understand the project structure.
ls -la | grep -E "package-lock.json|yarn.lock|pnpm-lock.yaml"

读取`package.json`以了解项目结构。

2. Dependency Compatibility Check

2. 依赖项兼容性检查

Read and analyze all dependencies from
package.json
:
bash
cat package.json
Check for known incompatible native modules:
Common problematic packages (check against current dependencies):
  • bcrypt
    → Use
    bcryptjs
    or
    @node-rs/bcrypt
    instead
  • sharp
    → Bun has native support, but may need version check
  • node-canvas
    → Limited support, check version compatibility
  • sqlite3
    → Use
    bun:sqlite
    instead
  • node-gyp
    dependent packages → May require alternative pure JS versions
  • fsevents
    → macOS-specific, usually optional dependency
  • esbuild
    → Bun has built-in bundler, may be redundant
Check workspace configuration (for monorepos):
bash
undefined
读取并分析
package.json
中的所有依赖项:
bash
cat package.json
检查已知不兼容的原生模块:
常见问题包(对照当前依赖项检查):
  • bcrypt
    → 改用
    bcryptjs
    @node-rs/bcrypt
  • sharp
    → Bun 提供原生支持,但可能需要检查版本
  • node-canvas
    → 支持有限,需检查版本兼容性
  • sqlite3
    → 改用
    bun:sqlite
  • 依赖
    node-gyp
    的包 → 可能需要替代的纯JS版本
  • fsevents
    → macOS专属,通常为可选依赖
  • esbuild
    → Bun 内置打包器,该包可能冗余
检查工作区配置(针对单体仓库):
bash
undefined

Check if workspaces are defined

Check if workspaces are defined

grep -n "workspaces" package.json
undefined
grep -n "workspaces" package.json
undefined

3. Generate Compatibility Report

3. 生成兼容性报告

Create a migration report file
BUN_MIGRATION_REPORT.md
:
markdown
undefined
创建迁移报告文件
BUN_MIGRATION_REPORT.md
markdown
undefined

Bun Migration Analysis Report

Bun 迁移分析报告

Project Overview

项目概述

  • Name: [project name]
  • Current Node Version: [version]
  • Package Manager: [npm/yarn/pnpm]
  • Project Type: [app/library/monorepo]
  • 名称: [项目名称]
  • 当前Node版本: [版本号]
  • 包管理器: [npm/yarn/pnpm]
  • 项目类型: [应用/库/单体仓库]

Dependency Analysis

依赖项分析

✅ Compatible Dependencies

✅ 兼容依赖项

[List dependencies that are Bun-compatible]
[列出Bun兼容的依赖项]

⚠️ Potentially Incompatible Dependencies

⚠️ 潜在不兼容依赖项

[List dependencies that may have issues]
Recommended Actions:
  • [Specific migration steps for each incompatible dependency]
[列出可能存在问题的依赖项]
建议操作:
  • [每个不兼容依赖项的具体迁移步骤]

🔄 Recommended Replacements

🔄 推荐替代方案

[List suggested package replacements]
[列出建议的包替换项]

Configuration Changes Needed

需要修改的配置

package.json

package.json

  • Update scripts to use
    bun
    instead of
    npm
    /
    yarn
  • Review and update
    engines
    field
  • Check
    type
    field (ESM vs CommonJS)
  • 将脚本更新为使用
    bun
    而非
    npm
    /
    yarn
  • 检查并更新
    engines
    字段
  • 确认
    type
    字段(ESM vs CommonJS)

tsconfig.json

tsconfig.json

  • Update
    moduleResolution
    to
    "bundler"
  • Add
    bun-types
    to types array
  • Set
    allowImportingTsExtensions
    to
    true
  • moduleResolution
    更新为
    "bundler"
  • 向types数组添加
    bun-types
  • allowImportingTsExtensions
    设为
    true

Build Configuration

构建配置

  • Review webpack/rollup/esbuild config (may use Bun bundler)
  • Update test runner config (use Bun test instead of Jest)
  • 检查webpack/rollup/esbuild配置(可改用Bun打包器)
  • 更新测试运行器配置(用Bun test替代Jest)

Migration Steps

迁移步骤

  1. Install Bun dependencies
  2. Update configuration files
  3. Run tests to verify compatibility
  4. Update CI/CD pipelines
  5. Update documentation
  1. 安装Bun依赖项
  2. 更新配置文件
  3. 运行测试以验证兼容性
  4. 更新CI/CD流水线
  5. 更新文档

Risk Assessment

风险评估

Low Risk: [List low-risk changes]
Medium Risk: [List items needing testing]
High Risk: [List critical compatibility concerns]
undefined
低风险: [列出低风险变更]
中风险: [列出需要测试的项]
高风险: [列出关键兼容性问题]
undefined

4. Backup Current State

4. 备份当前状态

Before making changes:
bash
undefined
在修改前:
bash
undefined

Create backup branch if in git repo

如果使用git仓库,创建备份分支

git branch -c backup-before-bun-migration
git branch -c backup-before-bun-migration

Or suggest user commits current state

或建议用户提交当前状态

git add -A git commit -m "Backup before Bun migration"
undefined
git add -A git commit -m "Backup before Bun migration"
undefined

5. Update package.json

5. 更新package.json

Read current package.json:
typescript
// Read and parse package.json
Update scripts to use Bun:
json
{
  "scripts": {
    "dev": "bun run --hot src/index.ts",
    "start": "bun run src/index.ts",
    "build": "bun build src/index.ts --outdir=dist",
    "test": "bun test",
    "typecheck": "bun run --bun tsc --noEmit",
    "lint": "bun run --bun eslint ."
  }
}
Update engines field:
json
{
  "engines": {
    "bun": ">=1.0.0"
  }
}
For libraries, add exports field if not present:
json
{
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js",
      "require": "./dist/index.cjs"
    }
  }
}
读取当前package.json:
typescript
// Read and parse package.json
更新脚本以使用Bun:
json
{
  "scripts": {
    "dev": "bun run --hot src/index.ts",
    "start": "bun run src/index.ts",
    "build": "bun build src/index.ts --outdir=dist",
    "test": "bun test",
    "typecheck": "bun run --bun tsc --noEmit",
    "lint": "bun run --bun eslint ."
  }
}
更新engines字段:
json
{
  "engines": {
    "bun": ">=1.0.0"
  }
}
对于库项目,若未添加则补充exports字段:
json
{
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js",
      "require": "./dist/index.cjs"
    }
  }
}

6. Update tsconfig.json

6. 更新tsconfig.json

Read current tsconfig:
bash
cat tsconfig.json
Apply Bun-specific updates:
json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "types": ["bun-types"],
    "lib": ["ES2022"],
    "jsx": "react-jsx",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "allowImportingTsExtensions": true,
    "noEmit": true
  }
}
Key changes explained:
  • moduleResolution: "bundler"
    → Uses Bun's module resolution
  • types: ["bun-types"]
    → Adds Bun's TypeScript definitions
  • allowImportingTsExtensions: true
    → Allows importing
    .ts
    files directly
  • noEmit: true
    → Bun runs TypeScript directly, no compilation needed
读取当前tsconfig:
bash
cat tsconfig.json
应用Bun专属更新:
json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "types": ["bun-types"],
    "lib": ["ES2022"],
    "jsx": "react-jsx",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "allowImportingTsExtensions": true,
    "noEmit": true
  }
}
关键变更说明:
  • moduleResolution: "bundler"
    → 使用Bun的模块解析逻辑
  • types: ["bun-types"]
    → 添加Bun的TypeScript类型定义
  • allowImportingTsExtensions: true
    → 允许直接导入
    .ts
    文件
  • noEmit: true
    → Bun可直接运行TypeScript,无需编译

7. Handle Workspace Configuration

7. 处理工作区配置

For monorepos with workspaces:
Verify workspace configuration is compatible:
json
{
  "workspaces": [
    "packages/*",
    "apps/*"
  ]
}
Bun supports the same workspace syntax as npm/yarn/pnpm.
Check workspace dependencies:
bash
undefined
针对带工作区的单体仓库:
验证工作区配置是否兼容:
json
{
  "workspaces": [
    "packages/*",
    "apps/*"
  ]
}
Bun支持与npm/yarn/pnpm相同的工作区语法。
检查工作区依赖项:
bash
undefined

Verify workspace structure

Verify workspace structure

find . -name "package.json" -not -path "/node_modules/"
undefined
find . -name "package.json" -not -path "/node_modules/"
undefined

8. Install Dependencies with Bun

8. 使用Bun安装依赖项

Remove old lockfiles:
bash
rm -f package-lock.json yarn.lock pnpm-lock.yaml
Install with Bun:
bash
bun install
This creates
bun.lockb
(Bun's binary lockfile).
For workspaces:
bash
bun install --frozen-lockfile  # Equivalent to npm ci
移除旧锁文件:
bash
rm -f package-lock.json yarn.lock pnpm-lock.yaml
使用Bun安装:
bash
bun install
此命令会创建
bun.lockb
(Bun的二进制锁文件)。
针对工作区:
bash
bun install --frozen-lockfile  # 等同于npm ci

9. Update Test Configuration

9. 更新测试配置

If using Jest, migrate to Bun test:
Create
bunfig.toml
for test configuration:
toml
[test]
preload = ["./tests/setup.ts"]
coverage = true
coverageThreshold = 0.8
Update test files:
  • Replace
    import { test, expect } from '@jest/globals'
  • With
    import { test, expect } from 'bun:test'
Jest compatibility notes:
  • Most Jest APIs work out of the box
  • jest.mock()
    → Use
    mock()
    from
    bun:test
  • Snapshot testing works the same
  • Coverage reports may differ slightly
若使用Jest,迁移至Bun test:
创建
bunfig.toml
用于测试配置:
toml
[test]
preload = ["./tests/setup.ts"]
coverage = true
coverageThreshold = 0.8
更新测试文件:
  • 替换
    import { test, expect } from '@jest/globals'
  • 改为
    import { test, expect } from 'bun:test'
Jest兼容性说明:
  • 大多数Jest API可直接使用
  • jest.mock()
    → 使用
    bun:test
    中的
    mock()
  • 快照测试用法一致
  • 覆盖率报告可能略有不同

10. Update Environment Configuration

10. 更新环境配置

Check .env files:
bash
ls -la | grep .env
Bun loads
.env
files automatically (same as dotenv package).
Update environment loading code:
  • Remove
    require('dotenv').config()
  • Bun loads
    .env
    by default
检查.env文件:
bash
ls -la | grep .env
Bun会自动加载
.env
文件(与dotenv包功能相同)。
更新环境加载代码:
  • 移除
    require('dotenv').config()
  • Bun默认会加载
    .env

11. Update Build Configuration

11. 更新构建配置

If using webpack/rollup/esbuild:
Consider replacing with Bun's built-in bundler:
typescript
// bun-build.ts
await Bun.build({
  entrypoints: ['./src/index.ts'],
  outdir: './dist',
  minify: true,
  splitting: true,
  sourcemap: 'external',
  target: 'bun',
});
Update build script in package.json:
json
{
  "scripts": {
    "build": "bun run bun-build.ts"
  }
}
若使用webpack/rollup/esbuild:
考虑替换为Bun内置的打包器:
typescript
// bun-build.ts
await Bun.build({
  entrypoints: ['./src/index.ts'],
  outdir: './dist',
  minify: true,
  splitting: true,
  sourcemap: 'external',
  target: 'bun',
});
更新package.json中的构建脚本:
json
{
  "scripts": {
    "build": "bun run bun-build.ts"
  }
}

12. Update CI/CD Configuration

12. 更新CI/CD配置

GitHub Actions example:
yaml
name: CI

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Setup Bun
        uses: oven-sh/setup-bun@v1
        with:
          bun-version: latest

      - name: Install dependencies
        run: bun install --frozen-lockfile

      - name: Run tests
        run: bun test

      - name: Type check
        run: bun run typecheck

      - name: Build
        run: bun run build
GitHub Actions示例:
yaml
name: CI

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Setup Bun
        uses: oven-sh/setup-bun@v1
        with:
          bun-version: latest

      - name: Install dependencies
        run: bun install --frozen-lockfile

      - name: Run tests
        run: bun test

      - name: Type check
        run: bun run typecheck

      - name: Build
        run: bun run build

13. Verification Steps

13. 验证步骤

Run these commands to verify migration:
bash
undefined
运行以下命令验证迁移结果:
bash
undefined

1. Check dependencies installed correctly

1. 检查依赖项是否正确安装

bun install
bun install

2. Run type checking

2. 运行类型检查

bun run --bun tsc --noEmit
bun run --bun tsc --noEmit

3. Run tests

3. 运行测试

bun test
bun test

4. Try development server

4. 尝试启动开发服务器

bun run dev
bun run dev

5. Test production build

5. 测试生产构建

bun run build
undefined
bun run build
undefined

14. Update Documentation

14. 更新文档

Create or update these documentation sections:
README.md:
markdown
undefined
创建或更新以下文档章节:
README.md:
markdown
undefined

Prerequisites

前置要求

  • Bun 1.0 or higher
  • Bun 1.0或更高版本

Installation

安装

bash
bun install
bash
bun install

Development

开发

bash
bun run dev
bash
bun run dev

Testing

测试

bash
bun test

**CHANGELOG.md entry:**
```markdown
bash
bun test

**CHANGELOG.md条目:**
```markdown

[Version] - [Date]

[版本号] - [日期]

Changed

变更

  • Migrated from Node.js/npm to Bun
  • Updated all dependencies to Bun-compatible versions
  • Replaced [specific packages] with [alternatives]
  • Updated TypeScript configuration for Bun
undefined
  • 从Node.js/npm迁移至Bun
  • 将所有依赖项更新为Bun兼容版本
  • 将[特定包]替换为[替代包]
  • 更新TypeScript配置以适配Bun
undefined

Common Migration Issues & Solutions

常见迁移问题与解决方案

Issue: Native Module Incompatibility

问题:原生模块不兼容

Symptoms:
error: Cannot find module "bcrypt"
Solution:
bash
undefined
症状:
error: Cannot find module "bcrypt"
解决方案:
bash
undefined

Replace with pure JavaScript alternative

替换为纯JavaScript替代包

bun remove bcrypt bun add bcryptjs
bun remove bcrypt bun add bcryptjs

Update imports

更新导入语句

Before: import bcrypt from 'bcrypt';

之前:import bcrypt from 'bcrypt';

After: import bcrypt from 'bcryptjs';

之后:import bcrypt from 'bcryptjs';

undefined
undefined

Issue: ESM/CommonJS Conflicts

问题:ESM/CommonJS冲突

Symptoms:
error: require() of ES Module not supported
Solution:
Add to
package.json
:
json
{
  "type": "module"
}
Or use
.mts
extension for ES modules and
.cts
for CommonJS.
症状:
error: require() of ES Module not supported
解决方案:
package.json
中添加:
json
{
  "type": "module"
}
或为ES模块使用
.mts
扩展名,为CommonJS使用
.cts
扩展名。

Issue: Path Alias Resolution

问题:路径别名解析失败

Symptoms:
error: Cannot resolve "@/components"
Solution:
Verify
tsconfig.json
paths match:
json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}
Bun respects TypeScript path aliases automatically.
症状:
error: Cannot resolve "@/components"
解决方案:
验证
tsconfig.json
中的路径配置是否匹配:
json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}
Bun会自动识别TypeScript路径别名。

Issue: Test Failures

问题:测试失败

Symptoms:
error: jest is not defined
Solution:
Update test imports:
typescript
// Before
import { describe, it, expect } from '@jest/globals';

// After
import { describe, it, expect } from 'bun:test';
症状:
error: jest is not defined
解决方案:
更新测试导入语句:
typescript
// 之前
import { describe, it, expect } from '@jest/globals';

// 之后
import { describe, it, expect } from 'bun:test';

Migration Checklist

迁移检查清单

Present this checklist to the user:
  • Bun installed and verified
  • Dependency compatibility analyzed
  • Migration report reviewed
  • Current state backed up (git commit/branch)
  • package.json
    scripts updated
  • tsconfig.json
    configured for Bun
  • Old lockfiles removed
  • Dependencies installed with
    bun install
  • Test configuration migrated
  • Tests passing with
    bun test
  • Build process verified
  • CI/CD updated for Bun
  • Documentation updated
  • Team notified of migration
向用户展示以下检查清单:
  • Bun已安装并验证
  • 已分析依赖项兼容性
  • 已审阅迁移报告
  • 已备份当前状态(git提交/分支)
  • 已更新package.json脚本
  • 已为Bun配置tsconfig.json
  • 已移除旧锁文件
  • 已使用
    bun install
    安装依赖项
  • 已迁移测试配置
  • bun test
    测试通过
  • 已验证构建流程
  • 已为Bun更新CI/CD
  • 已更新文档
  • 已通知团队迁移事宜

Post-Migration Performance Verification

迁移后性能验证

After migration, help user verify performance improvements:
bash
undefined
迁移完成后,协助用户验证性能提升:
bash
undefined

Compare install times

对比安装时间

time bun install # Should be 3-10x faster than npm
time bun install # 速度应比npm快3-10倍

Compare test execution

对比测试执行时间

time bun test # Should be faster than Jest
time bun test # 速度应快于Jest

Compare startup time

对比启动时间

time bun run src/index.ts # Should be 90% faster than ts-node
undefined
time bun run src/index.ts # 速度应比ts-node快90%
undefined

Rollback Procedure

回滚流程

If migration encounters critical issues:
bash
undefined
若迁移遇到严重问题:
bash
undefined

Return to backup branch

切换至备份分支

git checkout backup-before-bun-migration
git checkout backup-before-bun-migration

Or restore original state

或恢复至原始状态

git reset --hard HEAD~1
git reset --hard HEAD~1

Reinstall original dependencies

重新安装原始依赖项

npm install # or yarn/pnpm
undefined
npm install # 或yarn/pnpm
undefined

Completion

完成

Once migration is complete, provide summary:
  • ✅ Migration status (success/partial/issues)
  • ✅ List of changes made
  • ✅ Performance improvements observed
  • ✅ Any remaining manual steps
  • ✅ Links to Bun documentation for ongoing development
迁移完成后,提供总结:
  • ✅ 迁移状态(成功/部分完成/存在问题)
  • ✅ 已执行的变更列表
  • ✅ 观察到的性能提升
  • ✅ 剩余的手动步骤
  • ✅ 用于后续开发的Bun文档链接