mcpField
N
node-to-bun

node-to-bun

github.com/daleseo開発445 回インストール40 週間前に更新
リポジトリ

node-to-bun について

Node.js プロジェクトを Bun に移行する開発者向けのスキルです。依存関係の確認から設定変更、検証、ロールバックまで扱い、アプリ、ライブラリ、モノレポに対応します。

主な機能

  1. 01依存関係の互換性分析
  2. 02package.json と tsconfig の更新
  3. 03テストとビルドの移行ガイド
  4. 04移行レポートとチェックリスト
  5. 05検証とロールバック手順

活用シーン

  1. 01Bun 採用前の依存関係評価
  2. 02スクリプトと TypeScript 設定の更新
  3. 03Jest テストとビルド設定の移行
  4. 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/bcrypt を使用します
  • sharp → 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 commit/branch)
  • package.json のスクリプトを更新済み
  • tsconfig.json を Bun 向けに設定済み
  • 古いロックファイルを削除済み
  • bun install で依存関係をインストール済み
  • テスト設定を移行済み
  • bun test でテストが成功
  • ビルドプロセスを検証済み
  • Bun 向けに CI/CD を更新済み
  • ドキュメントを更新済み
  • チームに移行を通知済み

移行後のパフォーマンス検証

移行後、ユーザーがパフォーマンスの改善を検証できるよう支援します:

# 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 ドキュメントへのリンク

コメント