Agent Skills by ALSEL
Anthropic Claudeソフトウェア開発⭐ リポ 0品質スコア 50/100

bun-development

Bunランタイムを使用したモダンなJavaScript/TypeScript開発をサポートします。パッケージ管理、バンドル、テスト、Node.jsからの移行など幅広くカバーします。Bunの導入・活用やJS/TSの開発速度最適化、Node.jsからBunへの移行作業に際してお使いください。

description の原文を見る

Modern JavaScript/TypeScript development with Bun runtime. Covers package management, bundling, testing, and migration from Node.js. Use when working with Bun, optimizing JS/TS development speed, or migrating from Node.js to Bun.

SKILL.md 本文

⚡ Bun Development

Bun ランタイムを使用した高速で最新の JavaScript/TypeScript 開発(oven-sh/bun からインスピレーションを得ています)。

このスキルを使う時

このスキルは以下の場合に使用してください:

  • Bun で新しい JS/TS プロジェクトを開始する
  • Node.js から Bun への移行
  • 開発速度の最適化
  • Bun の組み込みツール(バンドラー、テストランナー)の使用
  • Bun 固有の問題のトラブルシューティング

1. はじめに

1.1 インストール

# macOS / Linux
curl -fsSL https://bun.sh/install | bash

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

# Homebrew
brew tap oven-sh/bun
brew install bun

# npm(必要な場合)
npm install -g bun

# アップグレード
bun upgrade

1.2 Bun を選ぶ理由

機能BunNode.js
起動時間~25ms~100ms+
パッケージ導入10-100倍高速ベースライン
TypeScriptネイティブトランスパイラが必要
JSXネイティブトランスパイラが必要
テストランナー組み込み外部(Jest, Vitest)
バンドラー組み込み外部(Webpack, esbuild)

2. プロジェクトセットアップ

2.1 新規プロジェクト作成

# プロジェクト初期化
bun init

# 以下を作成:
# ├── package.json
# ├── tsconfig.json
# ├── index.ts
# └── README.md

# 特定のテンプレートで
bun create <template> <project-name>

# 例
bun create react my-app        # React アプリ
bun create next my-app         # Next.js アプリ
bun create vite my-app         # Vite アプリ
bun create elysia my-api       # Elysia API

2.2 package.json

{
  "name": "my-bun-project",
  "version": "1.0.0",
  "module": "index.ts",
  "type": "module",
  "scripts": {
    "dev": "bun run --watch index.ts",
    "start": "bun run index.ts",
    "test": "bun test",
    "build": "bun build ./index.ts --outdir ./dist",
    "lint": "bunx eslint ."
  },
  "devDependencies": {
    "@types/bun": "latest"
  },
  "peerDependencies": {
    "typescript": "^5.0.0"
  }
}

2.3 tsconfig.json(Bun 最適化版)

{
  "compilerOptions": {
    "lib": ["ESNext"],
    "module": "esnext",
    "target": "esnext",
    "moduleResolution": "bundler",
    "moduleDetection": "force",
    "allowImportingTsExtensions": true,
    "noEmit": true,
    "composite": true,
    "strict": true,
    "downlevelIteration": true,
    "skipLibCheck": true,
    "jsx": "react-jsx",
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "allowJs": true,
    "types": ["bun-types"]
  }
}

3. パッケージ管理

3.1 パッケージのインストール

# package.json からインストール
bun install              # または 'bun i'

# 依存関係を追加
bun add express          # 通常の依存関係
bun add -d typescript    # 開発用依存関係
bun add -D @types/node   # 開発用依存関係(エイリアス)
bun add --optional pkg   # オプション依存関係

# 特定のレジストリから
bun add lodash --registry https://registry.npmmirror.com

# 特定バージョンをインストール
bun add react@18.2.0
bun add react@latest
bun add react@next

# Git から
bun add github:user/repo
bun add git+https://github.com/user/repo.git

3.2 削除と更新

# パッケージ削除
bun remove lodash

# パッケージ更新
bun update              # すべて更新
bun update lodash       # 特定パッケージを更新
bun update --latest     # 最新版に更新(範囲指定を無視)

# 更新可能項目の確認
bun outdated

3.3 bunx(npx 相当)

# パッケージバイナリを実行
bunx prettier --write .
bunx tsc --init
bunx create-react-app my-app

# 特定バージョンで実行
bunx -p typescript@4.9 tsc --version

# インストールなしで実行
bunx cowsay "Hello from Bun!"

3.4 ロックファイル

# bun.lockb はバイナリロックファイル(高速パース)
# デバッグ用にテキストロックファイルを生成:
bun install --yarn    # yarn.lock を作成

# 既存のロックファイルを信頼
bun install --frozen-lockfile

4. コード実行

4.1 基本的な実行

# TypeScript を直接実行(ビルドステップ不要!)
bun run index.ts

# JavaScript を実行
bun run index.js

# 引数付きで実行
bun run server.ts --port 3000

# package.json のスクリプト実行
bun run dev
bun run build

# 短形式(スクリプト用)
bun dev
bun build

4.2 ウォッチモード

# ファイル変更時に自動再起動
bun --watch run index.ts

# ホットリロード付き
bun --hot run server.ts

4.3 環境変数

// .env ファイルは自動的にロード!

// 環境変数にアクセス
const apiKey = Bun.env.API_KEY;
const port = Bun.env.PORT ?? "3000";

// または process.env を使用(Node.js 互換)
const dbUrl = process.env.DATABASE_URL;
# 特定の環境ファイルで実行
bun --env-file=.env.production run index.ts

5. 組み込み API

5.1 ファイルシステム(Bun.file)

// ファイル読み込み
const file = Bun.file("./data.json");
const text = await file.text();
const json = await file.json();
const buffer = await file.arrayBuffer();

// ファイル情報
console.log(file.size); // バイト数
console.log(file.type); // MIME タイプ

// ファイル書き込み
await Bun.write("./output.txt", "Hello, Bun!");
await Bun.write("./data.json", JSON.stringify({ foo: "bar" }));

// 大規模ファイルのストリーム
const reader = file.stream();
for await (const chunk of reader) {
  console.log(chunk);
}

5.2 HTTP サーバー(Bun.serve)

const server = Bun.serve({
  port: 3000,

  fetch(request) {
    const url = new URL(request.url);

    if (url.pathname === "/") {
      return new Response("Hello World!");
    }

    if (url.pathname === "/api/users") {
      return Response.json([
        { id: 1, name: "Alice" },
        { id: 2, name: "Bob" },
      ]);
    }

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

  error(error) {
    return new Response(`Error: ${error.message}`, { status: 500 });
  },
});

console.log(`Server running at http://localhost:${server.port}`);

5.3 WebSocket サーバー

const server = Bun.serve({
  port: 3000,

  fetch(req, server) {
    // WebSocket にアップグレード
    if (server.upgrade(req)) {
      return; // アップグレード完了
    }
    return new Response("Upgrade failed", { status: 500 });
  },

  websocket: {
    open(ws) {
      console.log("クライアント接続");
      ws.send("Welcome!");
    },

    message(ws, message) {
      console.log(`受信: ${message}`);
      ws.send(`Echo: ${message}`);
    },

    close(ws) {
      console.log("クライアント切断");
    },
  },
});

5.4 SQLite(Bun.sql)

import { Database } from "bun:sqlite";

const db = new Database("mydb.sqlite");

// テーブル作成
db.run(`
  CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    email TEXT UNIQUE
  )
`);

// 挿入
const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
insert.run("Alice", "alice@example.com");

// クエリ
const query = db.prepare("SELECT * FROM users WHERE name = ?");
const user = query.get("Alice");
console.log(user); // { id: 1, name: "Alice", email: "alice@example.com" }

// すべてクエリ
const allUsers = db.query("SELECT * FROM users").all();

5.5 パスワードハッシング

// パスワードハッシュ化
const password = "super-secret";
const hash = await Bun.password.hash(password);

// パスワード検証
const isValid = await Bun.password.verify(password, hash);
console.log(isValid); // true

// アルゴリズムオプション付き
const bcryptHash = await Bun.password.hash(password, {
  algorithm: "bcrypt",
  cost: 12,
});

6. テスト

6.1 基本的なテスト

// math.test.ts
import { describe, it, expect, beforeAll, afterAll } from "bun:test";

describe("Math operations", () => {
  it("adds two numbers", () => {
    expect(1 + 1).toBe(2);
  });

  it("subtracts two numbers", () => {
    expect(5 - 3).toBe(2);
  });
});

6.2 テスト実行

# すべてのテスト実行
bun test

# 特定ファイル実行
bun test math.test.ts

# パターンマッチング実行
bun test --grep "adds"

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

# カバレッジ付き
bun test --coverage

# タイムアウト
bun test --timeout 5000

6.3 マッチャー

import { expect, test } from "bun:test";

test("matchers", () => {
  // 等値性
  expect(1).toBe(1);
  expect({ a: 1 }).toEqual({ a: 1 });
  expect([1, 2]).toContain(1);

  // 比較
  expect(10).toBeGreaterThan(5);
  expect(5).toBeLessThanOrEqual(5);

  // 真偽値
  expect(true).toBeTruthy();
  expect(null).toBeNull();
  expect(undefined).toBeUndefined();

  // 文字列
  expect("hello").toMatch(/ell/);
  expect("hello").toContain("ell");

  // 配列
  expect([1, 2, 3]).toHaveLength(3);

  // 例外
  expect(() => {
    throw new Error("fail");
  }).toThrow("fail");

  // 非同期
  await expect(Promise.resolve(1)).resolves.toBe(1);
  await expect(Promise.reject("err")).rejects.toBe("err");
});

6.4 モッキング

import { mock, spyOn } from "bun:test";

// モック関数
const mockFn = mock((x: number) => x * 2);
mockFn(5);
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledWith(5);
expect(mockFn.mock.results[0].value).toBe(10);

// メソッドをスパイ
const obj = {
  method: () => "original",
};
const spy = spyOn(obj, "method").mockReturnValue("mocked");
expect(obj.method()).toBe("mocked");
expect(spy).toHaveBeenCalled();

7. バンドリング

7.1 基本的なビルド

# 本番用にバンドル
bun build ./src/index.ts --outdir ./dist

# オプション付き
bun build ./src/index.ts \
  --outdir ./dist \
  --target browser \
  --minify \
  --sourcemap

7.2 Build API

const result = await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  target: "browser", // または "bun", "node"
  minify: true,
  sourcemap: "external",
  splitting: true,
  format: "esm",

  // 外部パッケージ(バンドルしない)
  external: ["react", "react-dom"],

  // グローバル定義
  define: {
    "process.env.NODE_ENV": JSON.stringify("production"),
  },

  // 命名規則
  naming: {
    entry: "[name].[hash].js",
    chunk: "chunks/[name].[hash].js",
    asset: "assets/[name].[hash][ext]",
  },
});

if (!result.success) {
  console.error(result.logs);
}

7.3 実行可能ファイルへコンパイル

# スタンドアロン実行可能ファイル作成
bun build ./src/cli.ts --compile --outfile myapp

# クロスコンパイル
bun build ./src/cli.ts --compile --target=bun-linux-x64 --outfile myapp-linux
bun build ./src/cli.ts --compile --target=bun-darwin-arm64 --outfile myapp-mac

# 埋め込みアセット付き
bun build ./src/cli.ts --compile --outfile myapp --embed ./assets

8. Node.js からの移行

8.1 互換性

// ほとんどの Node.js API はそのまま動作
import fs from "fs";
import path from "path";
import crypto from "crypto";

// process はグローバル
console.log(process.cwd());
console.log(process.env.HOME);

// Buffer はグローバル
const buf = Buffer.from("hello");

// __dirname と __filename が動作
console.log(__dirname);
console.log(__filename);

8.2 一般的な移行ステップ

# 1. Bun をインストール
curl -fsSL https://bun.sh/install | bash

# 2. パッケージマネージャー置き換え
rm -rf node_modules package-lock.json
bun install

# 3. package.json のスクリプト更新
# "start": "node index.js" → "start": "bun run index.ts"
# "test": "jest" → "test": "bun test"

# 4. Bun タイプを追加
bun add -d @types/bun

8.3 Node.js との相違点

// ❌ Node.js 固有(動作しない可能性)
require("module")             // import を使用してください
require.resolve("pkg")        // import.meta.resolve を使用してください
__non_webpack_require__       // サポートされていません

// ✅ Bun の同等物
import pkg from "pkg";
const resolved = import.meta.resolve("pkg");
Bun.resolveSync("pkg", process.cwd());

// ❌ これらのグローバルは異なる
process.hrtime()              // Bun.nanoseconds() を使用してください
setImmediate()                // queueMicrotask() を使用してください

// ✅ Bun 固有機能
const file = Bun.file("./data.txt");  // 高速ファイル API
Bun.serve({ port: 3000, fetch: ... }); // 高速 HTTP サーバー
Bun.password.hash(password);           // 組み込みハッシング

9. パフォーマンスのコツ

9.1 Bun ネイティブ API を使用

// 遅い(Node.js 互換)
import fs from "fs/promises";
const content = await fs.readFile("./data.txt", "utf-8");

// 高速(Bun ネイティブ)
const file = Bun.file("./data.txt");
const content = await file.text();

9.2 HTTP に Bun.serve を使用

// 非推奨:Express/Fastify(オーバーヘッド)
import express from "express";
const app = express();

// 推奨:Bun.serve(ネイティブ、4-10倍高速)
Bun.serve({
  fetch(req) {
    return new Response("Hello!");
  },
});

// または Elysia を使用(Bun 最適化フレームワーク)
import { Elysia } from "elysia";
new Elysia().get("/", () => "Hello!").listen(3000);

9.3 本番用バンドル

# 本番用は常にバンドルしてミニファイ
bun build ./src/index.ts --outdir ./dist --minify --target node

# その後バンドルを実行
bun run ./dist/index.js

クイックリファレンス

タスクコマンド
プロジェクト初期化bun init
依存関係インストールbun install
パッケージ追加bun add <pkg>
スクリプト実行bun run <script>
ファイル実行bun run file.ts
ウォッチモードbun --watch run file.ts
テスト実行bun test
ビルドbun build ./src/index.ts --outdir ./dist
パッケージ実行bunx <pkg>

リソース

ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ

詳細情報

作者
davila7
リポジトリ
davila7/claude-code-templates
ライセンス
MIT
最終更新
不明

Source: https://github.com/davila7/claude-code-templates / ライセンス: MIT

関連スキル

汎用ソフトウェア開発⭐ リポ 39,967

doubt-driven-development

重要な判断はすべて、本番環境への展開前に新しい視点から対抗的レビューを実施します。速度より正確性が重要な場合、不慣れなコードを扱う場合、本番環境・セキュリティに関わるロジック・取り消し不可の操作など影響度が高い場合、または後でバグを修正するよりも今検証する方が効率的な場合に活用してください。

by addyosmani
汎用ソフトウェア開発⭐ リポ 1,175

apprun-skills

TypeScriptを使用したAppRunアプリケーションのMVU設計に関する総合的なガイダンスが得られます。コンポーネントパターン、イベントハンドリング、状態管理(非同期ジェネレータを含む)、パラメータと保護機能を備えたルーティング・ナビゲーション、vistestを使用したテストに対応しています。AppRunコンポーネントの設計・レビュー、ルートの配線、状態フローの管理、AppRunテストの作成時に活用してください。

by yysun
OpenAIソフトウェア開発⭐ リポ 797

desloppify

コードベースのヘルスチェックと技術負債の追跡ツールです。コード品質、技術負債、デッドコード、大規模ファイル、ゴッドクラス、重複関数、コードスメル、命名規則の問題、インポートサイクル、結合度の問題についてユーザーが質問した場合に使用してください。また、ヘルススコアの確認、次の改善項目の提案、クリーンアップ計画の作成をリクエストされた際にも対応します。29言語に対応しています。

by Git-on-my-level
汎用ソフトウェア開発⭐ リポ 39,967

debugging-and-error-recovery

テストが失敗したり、ビルドが壊れたり、動作が期待と異なったり、予期しないエラーが発生したりした場合に、体系的な根本原因デバッグをガイドします。推測ではなく、根本原因を見つけて修正するための体系的なアプローチが必要な場合に使用してください。

by addyosmani
汎用ソフトウェア開発⭐ リポ 39,967

test-driven-development

テスト駆動開発により実装を進めます。ロジックの実装、バグの修正、動作の変更など、あらゆる場面で活用できます。コードが正常に動作することを証明する必要がある場合、バグ報告を受けた場合、既存機能を修正する予定がある場合に使用してください。

by addyosmani
汎用ソフトウェア開発⭐ リポ 39,967

incremental-implementation

変更を段階的に実施します。複数のファイルに影響する機能や変更を実装する場合に使用してください。大量のコードを一度に書こうとしている場合や、タスクが一度では完結できないほど大きい場合に活用します。

by addyosmani
本サイトは GitHub 上で公開されているオープンソースの SKILL.md ファイルをクロール・インデックス化したものです。 各スキルの著作権は原作者に帰属します。掲載に問題がある場合は info@alsel.co.jp または /takedown フォームよりご連絡ください。
原作者: davila7 · davila7/claude-code-templates · ライセンス: MIT