bun-bundler について
Bun の JavaScript/TypeScript バンドラーを CLI と JavaScript API で使うためのスキルガイドです。ビルド対象、ローダー、コード分割、プラグイン、一般的なエラーを扱います。
主な機能
- 01CLI と JavaScript API によるビルド
- 02ブラウザー、Bun、Node 向けのビルド
- 03コード分割と圧縮
- 04組み込みローダーとカスタムローダー
- 05プラグインとビルドオプションの解説
活用シーン
- 01本番環境向けに TypeScript アプリをバンドル
- 02複数のエントリーポイントをビルド
- 03アセットやカスタムローダーを設定
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ secondsky/ claude-skills --skill bun-bundlerインストール後、Claude Code で/bun-bundlerを入力して読み込まれたか確認します。
同梱ファイルreferences/options.md
詳細
Bun バンドラー
Bun のバンドラーは、Bun のランタイムと同じエンジン上に構築された、高速な JavaScript/TypeScript バンドラーです。ネイティブのパフォーマンスを備えた、esbuild 互換の代替ツールです。
クイックスタート
CLI
# Basic bundle
bun build ./src/index.ts --outdir ./dist
# Production build
bun build ./src/index.ts --outdir ./dist --minify
# Multiple entry points
bun build ./src/index.ts ./src/worker.ts --outdir ./dist
JavaScript API
// Since Bun 1.2, Bun.build REJECTS on failure (throws).
// Wrap in try/catch to handle errors; pass { throw: false } to restore the
// old resolve-with-{ success, logs } contract if you prefer that style.
try {
const result = await Bun.build({
entrypoints: ["./src/index.ts"],
outdir: "./dist",
});
console.log(`Built ${result.outputs.length} files`);
} catch (err) {
console.error("Build failed:", err);
process.exit(1);
}
Bun.build のオプション
await Bun.build({
// Entry points (required)
entrypoints: ["./src/index.ts"],
// Output directory
outdir: "./dist",
// Target environment
target: "browser", // "browser" | "bun" | "node"
// Output format
format: "esm", // "esm" | "cjs" | "iife"
// Minification
minify: true, // or { whitespace: true, identifiers: true, syntax: true }
// Code splitting
splitting: true,
// Source maps
sourcemap: "external", // "none" | "inline" | "external" | "linked"
// Naming patterns
naming: {
entry: "[dir]/[name].[ext]",
chunk: "[name]-[hash].[ext]",
asset: "[name]-[hash].[ext]",
},
// Define globals
define: {
"process.env.NODE_ENV": JSON.stringify("production"),
},
// External packages
external: ["react", "react-dom"],
// Loaders
loader: {
".svg": "text",
".png": "file",
},
// Plugins
plugins: [myPlugin],
// Root directory
root: "./src",
// Public path for assets
publicPath: "/static/",
});
CLI フラグ
bun build <entrypoints> [flags]
| フラグ | 説明 |
|---|---|
--outdir | 出力ディレクトリ |
--outfile | 単一ファイルとして出力 |
--target | browser、bun、node |
--format | esm、cjs、iife |
--minify | 圧縮を有効化 |
--minify-whitespace | 空白のみを圧縮 |
--minify-identifiers | 識別子のみを圧縮 |
--minify-syntax | 構文のみを圧縮 |
--splitting | コード分割を有効化 |
--sourcemap | none、inline、external、linked |
--external | パッケージを外部として指定 |
--define | コンパイル時定数を定義 |
--loader | 拡張子に対応するカスタムローダー |
--public-path | アセットのパブリックパス |
--root | ルートディレクトリ |
--entry-naming | エントリーポイントの命名パターン |
--chunk-naming | チャンクの命名パターン |
--asset-naming | アセットの命名パターン |
対象環境
ブラウザー(デフォルト)
await Bun.build({
entrypoints: ["./src/index.ts"],
target: "browser",
outdir: "./dist",
});
Bun ランタイム
await Bun.build({
entrypoints: ["./src/server.ts"],
target: "bun",
outdir: "./dist",
});
Node.js
await Bun.build({
entrypoints: ["./src/server.ts"],
target: "node",
outdir: "./dist",
});
コード分割
await Bun.build({
entrypoints: ["./src/index.ts", "./src/admin.ts"],
splitting: true,
outdir: "./dist",
});
共有依存関係は自動的に抽出され、個別のチャンクになります。
ローダー
| ローダー | 拡張子 | 出力 |
|---|---|---|
js | .js、.mjs、.cjs | JavaScript |
jsx | .jsx | JavaScript |
ts | .ts、.mts、.cts | JavaScript |
tsx | .tsx | JavaScript |
json | .json | JavaScript |
toml | .toml | JavaScript |
text | - | 文字列のエクスポート |
file | - | ファイルパスのエクスポート |
base64 | - | Base64 文字列 |
dataurl | - | Data URL |
css | .css | CSS ファイル |
カスタムローダー:
await Bun.build({
entrypoints: ["./src/index.ts"],
loader: {
".svg": "text",
".png": "file",
".woff2": "file",
},
});
プラグイン
const myPlugin = {
name: "my-plugin",
setup(build) {
// Resolve hook
build.onResolve({ filter: /\.special$/ }, (args) => {
return { path: args.path, namespace: "special" };
});
// Load hook
build.onLoad({ filter: /.*/, namespace: "special" }, (args) => {
return {
contents: `export default "special"`,
loader: "js",
};
});
},
};
await Bun.build({
entrypoints: ["./src/index.ts"],
plugins: [myPlugin],
});
ビルド出力
// Bun 1.2+: Bun.build rejects on failure. Use try/catch to surface build
// errors (or pass { throw: false } and keep the legacy { success, logs } shape).
try {
const result = await Bun.build({
entrypoints: ["./src/index.ts"],
outdir: "./dist",
});
// Access outputs
for (const output of result.outputs) {
console.log(output.path); // File path
console.log(output.kind); // "entry-point" | "chunk" | "asset"
console.log(output.hash); // Content hash
console.log(output.loader); // Loader used
// Read content
const text = await output.text();
}
} catch (err) {
console.error("Build failed:", err);
process.exit(1);
}
よくあるパターン
本番ビルド
await Bun.build({
entrypoints: ["./src/index.ts"],
outdir: "./dist",
target: "browser",
minify: true,
sourcemap: "external",
splitting: true,
define: {
"process.env.NODE_ENV": JSON.stringify("production"),
},
});
ライブラリのビルド
await Bun.build({
entrypoints: ["./src/index.ts"],
outdir: "./dist",
target: "bun",
format: "esm",
external: ["*"], // Externalize all dependencies
sourcemap: "external",
});
ビルドスクリプト
// build.ts
// Bun 1.2+: Bun.build rejects on failure, so try/catch is the modern idiom.
try {
const result = await Bun.build({
entrypoints: ["./src/index.ts"],
outdir: "./dist",
minify: process.env.NODE_ENV === "production",
});
console.log(`Built ${result.outputs.length} files`);
} catch (err) {
console.error("Build failed:", err);
process.exit(1);
}
実行方法:bun run build.ts
よくあるエラー
| エラー | 原因 | 解決方法 |
|---|---|---|
Could not resolve | インポート先が見つからない | パッケージをインストールするか、パスを修正してください |
No matching export | 名前付きエクスポートが見つからない | エクスポート名を確認してください |
Unexpected token | 構文エラー | ソースコードを修正してください |
Target not supported | 無効なターゲット | browser、bun、node のいずれかを使用してください |
リファレンスを読み込むタイミング
次の場合は references/options.md を読み込みます:
- オプションの完全なリファレンスが必要な場合
- 高度な機能を設定する場合
次の場合は references/plugins.md を読み込みます:
- カスタムプラグインを作成する場合
- プラグイン API を理解する場合
次の場合は references/macros.md を読み込みます:
- コンパイル時マクロを使用する場合
- ビルド時にコードを生成する場合
コメント
Markdown 対応