node-to-bun
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNode.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 --versionAnalyze current project:
bash
undefined检查Bun是否已安装:
bash
bun --version分析当前项目:
bash
undefinedCheck 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.jsonbash
cat package.jsonCheck for known incompatible native modules:
Common problematic packages (check against current dependencies):
- → Use
bcryptorbcryptjsinstead@node-rs/bcrypt - → Bun has native support, but may need version check
sharp - → Limited support, check version compatibility
node-canvas - → Use
sqlite3insteadbun:sqlite - dependent packages → May require alternative pure JS versions
node-gyp - → macOS-specific, usually optional dependency
fsevents - → Bun has built-in bundler, may be redundant
esbuild
Check workspace configuration (for monorepos):
bash
undefined读取并分析中的所有依赖项:
package.jsonbash
cat package.json检查已知不兼容的原生模块:
常见问题包(对照当前依赖项检查):
- → 改用
bcrypt或bcryptjs@node-rs/bcrypt - → Bun 提供原生支持,但可能需要检查版本
sharp - → 支持有限,需检查版本兼容性
node-canvas - → 改用
sqlite3bun:sqlite - 依赖的包 → 可能需要替代的纯JS版本
node-gyp - → macOS专属,通常为可选依赖
fsevents - → Bun 内置打包器,该包可能冗余
esbuild
检查工作区配置(针对单体仓库):
bash
undefinedCheck if workspaces are defined
Check if workspaces are defined
grep -n "workspaces" package.json
undefinedgrep -n "workspaces" package.json
undefined3. Generate Compatibility Report
3. 生成兼容性报告
Create a migration report file :
BUN_MIGRATION_REPORT.mdmarkdown
undefined创建迁移报告文件:
BUN_MIGRATION_REPORT.mdmarkdown
undefinedBun 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 instead of
bun/npmyarn - Review and update field
engines - Check field (ESM vs CommonJS)
type
- 将脚本更新为使用而非
bun/npmyarn - 检查并更新字段
engines - 确认字段(ESM vs CommonJS)
type
tsconfig.json
tsconfig.json
- Update to
moduleResolution"bundler" - Add to types array
bun-types - Set to
allowImportingTsExtensionstrue
- 将更新为
moduleResolution"bundler" - 向types数组添加
bun-types - 将设为
allowImportingTsExtensionstrue
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
迁移步骤
- Install Bun dependencies
- Update configuration files
- Run tests to verify compatibility
- Update CI/CD pipelines
- Update documentation
- 安装Bun依赖项
- 更新配置文件
- 运行测试以验证兼容性
- 更新CI/CD流水线
- 更新文档
Risk Assessment
风险评估
Low Risk:
[List low-risk changes]
Medium Risk:
[List items needing testing]
High Risk:
[List critical compatibility concerns]
undefined低风险:
[列出低风险变更]
中风险:
[列出需要测试的项]
高风险:
[列出关键兼容性问题]
undefined4. Backup Current State
4. 备份当前状态
Before making changes:
bash
undefined在修改前:
bash
undefinedCreate 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"
undefinedgit add -A
git commit -m "Backup before Bun migration"
undefined5. Update package.json
5. 更新package.json
Read current package.json:
typescript
// Read and parse package.jsonUpdate 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.jsonApply 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:
- → Uses Bun's module resolution
moduleResolution: "bundler" - → Adds Bun's TypeScript definitions
types: ["bun-types"] - → Allows importing
allowImportingTsExtensions: truefiles directly.ts - → Bun runs TypeScript directly, no compilation needed
noEmit: true
读取当前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
}
}关键变更说明:
- → 使用Bun的模块解析逻辑
moduleResolution: "bundler" - → 添加Bun的TypeScript类型定义
types: ["bun-types"] - → 允许直接导入
allowImportingTsExtensions: true文件.ts - → Bun可直接运行TypeScript,无需编译
noEmit: true
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
undefinedVerify workspace structure
Verify workspace structure
find . -name "package.json" -not -path "/node_modules/"
undefinedfind . -name "package.json" -not -path "/node_modules/"
undefined8. Install Dependencies with Bun
8. 使用Bun安装依赖项
Remove old lockfiles:
bash
rm -f package-lock.json yarn.lock pnpm-lock.yamlInstall with Bun:
bash
bun installThis creates (Bun's binary lockfile).
bun.lockbFor 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的二进制锁文件)。
bun.lockb针对工作区:
bash
bun install --frozen-lockfile # 等同于npm ci9. Update Test Configuration
9. 更新测试配置
If using Jest, migrate to Bun test:
Create for test configuration:
bunfig.tomltoml
[test]
preload = ["./tests/setup.ts"]
coverage = true
coverageThreshold = 0.8Update 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
- → Use
jest.mock()frommock()bun:test - Snapshot testing works the same
- Coverage reports may differ slightly
若使用Jest,迁移至Bun test:
创建用于测试配置:
bunfig.tomltoml
[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:testmock() - 快照测试用法一致
- 覆盖率报告可能略有不同
10. Update Environment Configuration
10. 更新环境配置
Check .env files:
bash
ls -la | grep .envBun loads files automatically (same as dotenv package).
.envUpdate environment loading code:
- Remove
require('dotenv').config() - Bun loads by default
.env
检查.env文件:
bash
ls -la | grep .envBun会自动加载文件(与dotenv包功能相同)。
.env更新环境加载代码:
- 移除
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 buildGitHub 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 build13. Verification Steps
13. 验证步骤
Run these commands to verify migration:
bash
undefined运行以下命令验证迁移结果:
bash
undefined1. 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
undefinedbun run build
undefined14. Update Documentation
14. 更新文档
Create or update these documentation sections:
README.md:
markdown
undefined创建或更新以下文档章节:
README.md:
markdown
undefinedPrerequisites
前置要求
Installation
安装
bash
bun installbash
bun installDevelopment
开发
bash
bun run devbash
bun run devTesting
测试
bash
bun test
**CHANGELOG.md entry:**
```markdownbash
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
undefinedCommon Migration Issues & Solutions
常见迁移问题与解决方案
Issue: Native Module Incompatibility
问题:原生模块不兼容
Symptoms:
error: Cannot find module "bcrypt"Solution:
bash
undefined症状:
error: Cannot find module "bcrypt"解决方案:
bash
undefinedReplace 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';
undefinedundefinedIssue: ESM/CommonJS Conflicts
问题:ESM/CommonJS冲突
Symptoms:
error: require() of ES Module not supportedSolution:
Add to :
package.jsonjson
{
"type": "module"
}Or use extension for ES modules and for CommonJS.
.mts.cts症状:
error: require() of ES Module not supported解决方案:
在中添加:
package.jsonjson
{
"type": "module"
}或为ES模块使用扩展名,为CommonJS使用扩展名。
.mts.ctsIssue: Path Alias Resolution
问题:路径别名解析失败
Symptoms:
error: Cannot resolve "@/components"Solution:
Verify paths match:
tsconfig.jsonjson
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}Bun respects TypeScript path aliases automatically.
症状:
error: Cannot resolve "@/components"解决方案:
验证中的路径配置是否匹配:
tsconfig.jsonjson
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}Bun会自动识别TypeScript路径别名。
Issue: Test Failures
问题:测试失败
Symptoms:
error: jest is not definedSolution:
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)
- scripts updated
package.json - configured for Bun
tsconfig.json - 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
undefinedCompare 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
undefinedtime bun run src/index.ts # 速度应比ts-node快90%
undefinedRollback Procedure
回滚流程
If migration encounters critical issues:
bash
undefined若迁移遇到严重问题:
bash
undefinedReturn 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
undefinednpm install # 或yarn/pnpm
undefinedCompletion
完成
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文档链接