bun
Bunランタイム、パッケージマネージャー、バンドラー、テストランナーです。 Bunでスクリプトを実行する場合、パッケージを管理する場合、Bun.serveでHTTPサーバーを立ち上げる場合、Bun.sql/bun:sqlite/Bun.redisでデータベースをクエリする場合、$でシェルスクリプティングを行う場合、S3やファイルI/Oを使用する場合、bun:testでテストを作成する場合、バンドルまたは実行可能ファイルにコンパイルする場合、またはspawn、glob、semver、FFI、workers、plugins、HTMLRewriterなど、Bun固有のAPIを使用する場合に利用できます。
description の原文を見る
Bun runtime, package manager, bundler, and test runner. Use when running scripts with bun, managing packages, serving HTTP with Bun.serve, querying databases with Bun.sql/bun:sqlite/Bun.redis, shell scripting with $, using S3/file I/O, writing tests with bun:test, bundling or compiling to executable, or using any Bun-specific API (spawn, glob, semver, FFI, workers, plugins, HTMLRewriter).
SKILL.md 本文
Bun
クイックスタート
# インストール
curl -fsSL https://bun.sh/install | bash
# プロジェクト初期化
bun init
# TypeScriptを直接実行
bun run index.ts
# ウォッチモード(変更時にハードリスタート)
bun --watch index.ts
# ホットリロード(グローバル状態を保持、リスタートなし)
bun --hot server.ts
パッケージ管理
bun install # すべての依存関係をインストール
bun add express # 依存関係を追加
bun add -d @types/node # 開発用依存関係を追加
bun remove lodash # 削除
bun update # すべてを更新
bun update --latest # semverの範囲を無視
bunx prettier --write . # パッケージバイナリを実行(npxと同等)
bun patch express # node_modulesの依存関係にパッチを適用
ワークスペース
// ルートpackage.json
{ "workspaces": ["packages/*"] }
// 子package.json
{ "dependencies": { "shared": "workspace:*" } }
bun install --filter "pkg-*" # フィルタリングされたワークスペースをインストール
環境変数
.envファイルは以下の順序で自動読み込みされます:.env → .env.$(NODE_ENV) → .env.local
Bun.env.API_KEY // Bun固有
process.env.API_KEY // Node.js互換
import.meta.env.API_KEY
bun --env-file=.env.staging run start
HTTPサーバー
Bun.serve({
port: 3000,
routes: {
"/": new Response("Home"),
"/users/:id": (req) => Response.json({ id: req.params.id }),
"/api/posts": {
GET: () => Response.json([]),
POST: async (req) => Response.json(await req.json(), { status: 201 }),
},
"/api/*": Response.json({ error: "Not found" }, { status: 404 }),
"/favicon.ico": Bun.file("./favicon.ico"),
},
fetch(req) {
return new Response("Not Found", { status: 404 });
},
});
WebSocketアップグレード
Bun.serve({
fetch(req, server) {
if (server.upgrade(req, { data: { userId: "123" } })) return;
return new Response("Not a WebSocket", { status: 400 });
},
websocket: {
open(ws) { ws.subscribe("chat"); },
message(ws, msg) { ws.publish("chat", msg); },
close(ws) {},
},
});
フルスタック(HTMLインポート)
import homepage from "./index.html";
Bun.serve({
routes: { "/": homepage },
development: true, // HMRを有効化
});
クッキー、静的ルート、TLS、サーバーライフサイクル、メトリクスについてはreferences/http-server.mdを参照してください。
データベース
Bun.sql(Postgres / MySQL / SQLite)
import { sql, SQL } from "bun";
// DATABASE_URL / POSTGRES_URL / MYSQL_URLを自動読み込み
const users = await sql`SELECT * FROM users WHERE active = ${true}`;
// 明示的な接続
const pg = new SQL("postgres://user:pass@localhost:5432/mydb");
const mysql = new SQL("mysql://user:pass@localhost:3306/mydb");
const sqlite = new SQL(":memory:");
// オブジェクトヘルパーで挿入
const [user] = await sql`INSERT INTO users ${sql({ name: "Alice", email: "a@b.com" })} RETURNING *`;
// 一括挿入
await sql`INSERT INTO users ${sql([user1, user2, user3])}`;
// トランザクション
await sql.begin(async (tx) => {
const [u] = await tx`INSERT INTO users ${sql({ name: "Bob" })} RETURNING *`;
await tx`INSERT INTO accounts (user_id) VALUES (${u.id})`;
});
bun:sqlite(同期、組み込み)
import { Database } from "bun:sqlite";
const db = new Database("app.db");
db.run("CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, val TEXT)");
const row = db.query("SELECT * FROM kv WHERE key = ?").get("foo");
const all = db.query("SELECT * FROM kv").all();
// クラスマッピング
class User { id!: number; name!: string; }
const users = db.query("SELECT * FROM users").as(User).all();
Bun.redis
import { redis } from "bun";
await redis.set("key", "value", { ex: 60 });
const val = await redis.get("key");
await redis.del("key");
await redis.hmset("user:1", { name: "Alice", role: "admin" });
トランザクション、セーブポイント、MySQL/SQLiteの詳細、Redisパブ/サブ、接続オプションについてはreferences/database.mdを参照してください。
シェル($)
import { $ } from "bun";
// 実行して標準出力に出力
await $`echo "Hello"`;
// 出力をキャプチャ
const text = await $`ls -la`.text();
const data = await $`cat config.json`.json();
for await (const line of $`cat file.txt`.lines()) { }
// パイプ
await $`cat file.txt | grep "pattern" | wc -l`;
// JSオブジェクトからのリダイレクト
await $`cat < ${new Response("data")} > ${Bun.file("out.txt")}`;
// エラーハンドリング
const { exitCode } = await $`may-fail`.nothrow().quiet();
// 設定
$.cwd("/tmp");
$.env({ ...process.env, NODE_ENV: "production" });
セキュリティ: 補間された変数は自動的にエスケープされます(シェルインジェクションなし)。バイパスするには{ raw: str }を使用します。
references/shell.mdを参照して、ビルトイン、コマンド置換、ブレース展開について確認してください。
ファイルI/O&S3
// 読み込み
const file = Bun.file("data.json");
const json = await file.json(); // また:.text()、.bytes()、.stream()、.arrayBuffer()
console.log(file.size, file.type); // バイト単位のサイズ、MIMEタイプ
// 書き込み
await Bun.write("out.txt", "hello");
await Bun.write(Bun.file("copy.bin"), Bun.file("src.bin")); // ファイルをコピー
// インクリメンタル書き込み
const writer = Bun.file("log.txt").writer();
writer.write("line 1\n");
writer.write("line 2\n");
writer.end();
// S3
import { s3 } from "bun";
const obj = s3.file("data.json");
const data = await obj.json();
await obj.write(JSON.stringify({ ok: true }));
const url = obj.presign({ expiresIn: 3600, method: "PUT" });
await obj.delete();
// s3://プロトコル
const res = await fetch("s3://bucket/file.txt");
// Glob
const glob = new Bun.Glob("**/*.ts");
for await (const path of glob.scan(".")) console.log(path);
S3認証情報、マルチパートアップロード、ストリーム、ハッシング、semverについてはreferences/file-io.mdを参照してください。
テスト
import { test, expect, describe, mock, spyOn, beforeEach } from "bun:test";
describe("math", () => {
test("adds", () => expect(1 + 1).toBe(2));
test.each([
[1, 2, 3],
[4, 5, 9],
])("%i + %i = %i", (a, b, expected) => {
expect(a + b).toBe(expected);
});
test.skip("wip", () => {});
test.todo("implement later");
});
// モック関数
const fn = mock(() => 42);
fn();
expect(fn).toHaveBeenCalled();
// モジュールモッキング
mock.module("./db", () => ({
query: mock(() => []),
}));
// スパイ
const spy = spyOn(console, "log");
console.log("test");
expect(spy).toHaveBeenCalledWith("test");
// スナップショット
test("snap", () => {
expect({ a: 1, b: "hello" }).toMatchSnapshot();
});
bun test # すべてのテストを実行
bun test --watch # ウォッチモード
bun test --coverage # カバレッジ付き
bun test --update-snapshots # スナップショットを更新
bun test --bail # 最初の失敗で停止
bun test --test-name-pattern "add" # 名前でフィルタリング
すべてのマッチャー、ライフサイクルフック、型テスト、リトライ/リピート、DOMテストについてはreferences/testing.mdを参照してください。
バンドラーとコンパイル
// ブラウザ用にバンドル
const result = await Bun.build({
entrypoints: ["./src/index.ts"],
outdir: "./dist",
splitting: true,
minify: true,
sourcemap: "linked",
target: "browser", // または "bun"、"node"
});
if (!result.success) {
for (const log of result.logs) console.error(log);
}
# スタンドアロン実行可能ファイルにコンパイル
bun build --compile --minify --sourcemap --bytecode ./app.ts --outfile myapp
# クロスコンパイル
bun build --compile --target=bun-linux-x64 ./app.ts --outfile myapp-linux
bun build --compile --target=bun-darwin-arm64 ./app.ts --outfile myapp-mac
// 実行可能ファイルに埋め込むファイル
import icon from "./icon.png" with { type: "file" };
import db from "./data.db" with { type: "sqlite", embed: "true" };
すべてのビルドオプション、プラグイン、クロスコンパイル対象、Windowsオプション、トランスパイラーAPIについてはreferences/bundler.mdを参照してください。
子プロセス
// 非同期
const proc = Bun.spawn(["ls", "-la"], {
cwd: "/tmp",
stdout: "pipe",
});
const output = await new Response(proc.stdout).text();
await proc.exited;
// 同期
const { stdout, exitCode } = Bun.spawnSync(["echo", "hi"]);
// タイムアウト + 中止
const ctrl = new AbortController();
Bun.spawn(["sleep", "100"], { signal: ctrl.signal, timeout: 5000 });
// bunプロセス間のIPC
const child = Bun.spawn(["bun", "worker.ts"], {
ipc(msg) { console.log("from child:", msg); },
});
child.send({ type: "start" });
設定(bunfig.toml)
# 一般的なオプション
preload = ["./setup.ts"]
logLevel = "warn"
[run]
shell = "bun" # システムシェルの代わりにBunシェルを使用
bun = true # スクリプト内でnodeをbunのエイリアスに
[test]
preload = ["./test-setup.ts"]
coverage = true
coverageThreshold = 0.8
retry = 2
[install]
exact = true # 正確なバージョンを固定
frozenLockfile = true # CI:ロックファイルが古い場合は失敗
auto = "fallback" # 欠落パッケージを自動インストール
bunfig.tomlの完全なリファレンスについてはreferences/configuration.mdを参照してください。
リファレンスインデックス
| トピック | リファレンス |
|---|---|
| HTTPサーバー、ルーティング、WebSocket、クッキー、フルスタック | references/http-server.md |
| Bun.sql、bun:sqlite、Bun.redis | references/database.md |
| TCP、UDP、DNS、fetch | references/networking.md |
| Bunシェル($) | references/shell.md |
| bun:test、モッキング、スナップショット、カバレッジ | references/testing.md |
| Bun.build、実行可能ファイルへのコンパイル、プラグイン | references/bundler.md |
| Bun.file、S3、Glob、ストリーム、ハッシング、semver | references/file-io.md |
| bunfig.toml完全リファレンス | references/configuration.md |
| Workers、HTMLRewriter、FFI、Cコンパイラー、シークレット、Node.js互換性 | references/advanced.md |
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- fellipeutaka
- リポジトリ
- fellipeutaka/kanpeki
- ライセンス
- MIT
- 最終更新
- 2026/3/10
Source: https://github.com/fellipeutaka/kanpeki / ライセンス: MIT