Bun 2.0 - JavaScriptランタイムの新時代

10分 で読める | 2025.01.10

Bun 2.0の概要

Bun 2.0は、Zigで書かれた高速JavaScriptランタイムの最新メジャーバージョンです。Node.jsとの互換性を大幅に強化し、本番環境での採用がさらに容易になりました。

主な新機能

Windows完全サポート

Bun 2.0でWindowsネイティブ対応が完了しました。

# Windows PowerShell
powershell -c "irm bun.sh/install.ps1 | iex"

# WSLなしで動作
bun run dev

Node.js互換性の強化

ほぼ全てのNode.js APIが利用可能になりました。

// 互換性向上
import { createServer } from 'node:http';
import { Worker } from 'node:worker_threads';
import { spawn } from 'node:child_process';
import cluster from 'node:cluster';

// これらが完全に動作
const server = createServer((req, res) => {
  res.end('Hello from Bun!');
});

パフォーマンス改善

# ベンチマーク比較(1秒あたりのリクエスト数)
# Bun 2.0:   150,000 req/s
# Node.js:   45,000 req/s
# Deno:      60,000 req/s

Bun.sql(SQLiteクライアント)

新しいSQLite APIが追加されました。

import { sql } from 'bun';

// タグ付きテンプレートリテラル
const users = await sql`SELECT * FROM users WHERE id = ${userId}`;

// プリペアドステートメント
const stmt = sql.prepare('SELECT * FROM users WHERE name LIKE ?');
const results = await stmt.all('%Alice%');

// トランザクション
await sql.transaction(async (tx) => {
  await tx`INSERT INTO users (name) VALUES ('Alice')`;
  await tx`INSERT INTO users (name) VALUES ('Bob')`;
});

Bun.serve の機能強化

Bun.serve({
  port: 3000,

  // 静的ファイル配信
  static: {
    '/': './public/index.html',
    '/assets': './public/assets',
  },

  // WebSocket
  websocket: {
    message(ws, message) {
      ws.send(`Echo: ${message}`);
    },
  },

  // HTTP
  fetch(req) {
    const url = new URL(req.url);

    if (url.pathname === '/api/data') {
      return Response.json({ message: 'Hello' });
    }

    return new Response('Not Found', { status: 404 });
  },
});

Hot Module Replacement(HMR)

開発時のホットリロードが大幅に改善されました。

// bun --hot で起動
// ファイル変更時に状態を維持したまま更新

Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response('Hello');
  },
});

// module.hot APIも利用可能
if (import.meta.hot) {
  import.meta.hot.accept();
}

パッケージマネージャー

高速インストール

# 同じpackage.jsonのインストール時間
# npm:  15秒
# yarn: 12秒
# pnpm: 8秒
# bun:  1.5秒

ワークスペースサポート

// package.json
{
  "workspaces": [
    "packages/*",
    "apps/*"
  ]
}
# 全ワークスペースのインストール
bun install

# 特定のワークスペースでコマンド実行
bun --filter packages/ui build

バンドラー改善

# 本番ビルド
bun build ./src/index.ts --outdir ./dist --minify

# 複数エントリーポイント
bun build ./src/client.ts ./src/server.ts --outdir ./dist --splitting

# ソースマップ
bun build ./src/index.ts --outdir ./dist --sourcemap=external

Tree Shaking

// 未使用のコードが自動的に除去
import { used } from './utils';

// unusedはバンドルに含まれない
export function main() {
  return used();
}

テストランナー

// sum.test.ts
import { expect, test, describe, beforeAll, mock } from 'bun:test';

describe('math', () => {
  test('adds numbers', () => {
    expect(1 + 2).toBe(3);
  });

  test('mocking', () => {
    const fn = mock(() => 42);
    expect(fn()).toBe(42);
    expect(fn).toHaveBeenCalled();
  });
});
# テスト実行
bun test

# カバレッジ
bun test --coverage

# ウォッチモード
bun test --watch

Node.jsからの移行

package.json

{
  "scripts": {
    "dev": "bun run --hot src/index.ts",
    "build": "bun build src/index.ts --outdir dist",
    "test": "bun test",
    "start": "bun run dist/index.js"
  }
}

互換性チェック

# 互換性レポート
bunx bun-types check

# パッケージの互換性確認
bun pm ls --json | bunx check-node-compat

今後の展望

  • React Server Componentsの完全サポート
  • より深いNode.js互換性
  • パフォーマンスのさらなる向上

関連記事

← 一覧に戻る