关于 node-to-bun
此技能指导开发者将 Node.js 项目迁移到 Bun,涵盖依赖检查、配置调整、验证和回滚,适用于应用、库及 monorepo。
主要功能
- 01依赖兼容性分析
- 02更新 package.json 和 tsconfig
- 03测试与构建迁移指导
- 04迁移报告与检查清单
- 05验证及回滚步骤
适用场景
- 01采用 Bun 前评估依赖
- 02更新项目脚本和 TypeScript 设置
- 03迁移 Jest 测试与构建配置
- 04检查迁移结果并规划回滚
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ daleseo/ bun-skills --skill node-to-bun安装后在 Claude Code 中输入/node-to-bun确认已加载。
附带文件references/compatibility-matrix.md
详细介绍
从 Node.js 迁移到 Bun
你将协助把现有的 Node.js 项目迁移到 Bun。这包括分析依赖项、更新配置并确保兼容性。
迁移工作流
1. 迁移前分析
检查是否已安装 Bun:
bun --version
分析当前项目:
# Check Node.js version
node --version
# Check package manager
ls -la | grep -E "package-lock.json|yarn.lock|pnpm-lock.yaml"
读取 package.json,了解项目结构。
2. 依赖项兼容性检查
读取并分析 package.json 中的所有依赖项:
cat package.json
检查已知的不兼容原生模块:
常见的问题软件包(请对照当前依赖项进行检查):
bcrypt→ 改用bcryptjs或@node-rs/bcryptsharp→ Bun 原生支持,但可能需要检查版本node-canvas→ 支持有限,请检查版本兼容性sqlite3→ 改用bun:sqlite- 依赖
node-gyp的软件包 → 可能需要改用纯 JavaScript 替代版本 fsevents→ macOS 专用,通常为可选依赖项esbuild→ Bun 内置了打包器,可能不再需要
检查工作区配置(适用于单体仓库):
# Check if workspaces are defined
grep -n "workspaces" package.json
3. 生成兼容性报告
创建迁移报告文件 BUN_MIGRATION_REPORT.md:
# Bun Migration Analysis Report
## Project Overview
- **Name**: [project name]
- **Current Node Version**: [version]
- **Package Manager**: [npm/yarn/pnpm]
- **Project Type**: [app/library/monorepo]
## Dependency Analysis
### ✅ Compatible Dependencies
[List dependencies that are Bun-compatible]
### ⚠️ 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
- [ ] Update scripts to use `bun` instead of `npm`/`yarn`
- [ ] Review and update `engines` field
- [ ] Check `type` field (ESM vs CommonJS)
### tsconfig.json
- [ ] Update `moduleResolution` to `"bundler"`
- [ ] Add `bun-types` to types array
- [ ] Set `allowImportingTsExtensions` to `true`
### Build Configuration
- [ ] Review webpack/rollup/esbuild config (may use Bun bundler)
- [ ] Update test runner config (use Bun test instead of 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
## Risk Assessment
**Low Risk:**
[List low-risk changes]
**Medium Risk:**
[List items needing testing]
**High Risk:**
[List critical compatibility concerns]
4. 备份当前状态
进行更改前:
# Create backup branch if in git repo
git branch -c backup-before-bun-migration
# Or suggest user commits current state
git add -A
git commit -m "Backup before Bun migration"
5. 更新 package.json
读取当前的 package.json:
// Read and parse package.json
更新脚本以使用 Bun:
{
"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 字段:
{
"engines": {
"bun": ">=1.0.0"
}
}
对于库,如果不存在 exports 字段,请添加:
{
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
}
}
6. 更新 tsconfig.json
读取当前的 tsconfig:
cat tsconfig.json
应用 Bun 专用更新:
{
"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. 处理工作区配置
适用于使用工作区的单体仓库:
确认工作区配置兼容:
{
"workspaces": [
"packages/*",
"apps/*"
]
}
Bun 支持与 npm/yarn/pnpm 相同的工作区语法。
检查工作区依赖项:
# Verify workspace structure
find . -name "package.json" -not -path "*/node_modules/*"
8. 使用 Bun 安装依赖项
移除旧的锁文件:
rm -f package-lock.json yarn.lock pnpm-lock.yaml
使用 Bun 安装:
bun install
这会生成 bun.lockb(Bun 的二进制锁文件)。
适用于工作区:
bun install --frozen-lockfile # Equivalent to npm ci
9. 更新测试配置
如果使用 Jest,请迁移到 Bun test:
创建用于测试配置的 bunfig.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. 更新环境配置
检查 .env 文件:
ls -la | grep .env
Bun 会自动加载 .env 文件(与 dotenv 软件包相同)。
更新环境加载代码:
- 移除
require('dotenv').config() - Bun 默认会加载
.env
11. 更新构建配置
如果使用 webpack/rollup/esbuild:
可以考虑改用 Bun 内置的打包器:
// bun-build.ts
await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
minify: true,
splitting: true,
sourcemap: 'external',
target: 'bun',
});
更新 package.json 中的构建脚本:
{
"scripts": {
"build": "bun run bun-build.ts"
}
}
12. 更新 CI/CD 配置
GitHub Actions 示例:
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. 验证步骤
运行以下命令以验证迁移:
# 1. Check dependencies installed correctly
bun install
# 2. Run type checking
bun run --bun tsc --noEmit
# 3. Run tests
bun test
# 4. Try development server
bun run dev
# 5. Test production build
bun run build
14. 更新文档
创建或更新以下文档部分:
README.md:
## Prerequisites
- [Bun](https://bun.sh) 1.0 or higher
## Installation
```bash
bun install
开发
bun run dev
测试
bun test
**CHANGELOG.md entry:**
```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
常见迁移问题及解决方案
问题:原生模块不兼容
症状:
error: Cannot find module "bcrypt"
解决方案:
# Replace with pure JavaScript alternative
bun remove bcrypt
bun add bcryptjs
# Update imports
# Before: import bcrypt from 'bcrypt';
# After: import bcrypt from 'bcryptjs';
问题:ESM/CommonJS 冲突
症状:
error: require() of ES Module not supported
解决方案:
在 package.json 中添加:
{
"type": "module"
}
或者,ES 模块使用 .mts 扩展名,CommonJS 使用 .cts 扩展名。
问题:路径别名解析
症状:
error: Cannot resolve "@/components"
解决方案:
确认 tsconfig.json 中的 paths 配置一致:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
Bun 会自动遵循 TypeScript 路径别名。
问题:测试失败
症状:
error: jest is not defined
解决方案:
更新测试导入:
// Before
import { describe, it, expect } from '@jest/globals';
// After
import { describe, it, expect } from 'bun:test';
迁移清单
向用户展示此清单:
- 已安装并验证 Bun
- 已分析依赖项兼容性
- 已审查迁移报告
- 已备份当前状态(git 提交/分支)
- 已更新
package.json脚本 - 已配置适用于 Bun 的
tsconfig.json - 已删除旧锁文件
- 已使用
bun install安装依赖项 - 已迁移测试配置
- 使用
bun test测试通过 - 已验证构建流程
- 已更新 CI/CD 以适配 Bun
- 已更新文档
- 已通知团队进行迁移
迁移后的性能验证
迁移后,帮助用户验证性能提升:
# Compare install times
time bun install # Should be 3-10x faster than npm
# Compare test execution
time bun test # Should be faster than Jest
# Compare startup time
time bun run src/index.ts # Should be 90% faster than ts-node
回滚流程
如果迁移遇到严重问题:
# Return to backup branch
git checkout backup-before-bun-migration
# Or restore original state
git reset --hard HEAD~1
# Reinstall original dependencies
npm install # or yarn/pnpm
完成
迁移完成后,提供摘要:
- ✅ 迁移状态(成功/部分完成/存在问题)
- ✅ 所做更改列表
- ✅ 观察到的性能提升
- ✅ 任何剩余的手动步骤
- ✅ Bun 文档链接,供后续开发参考