bun-build について
bun-buildは、Bunのネイティブバンドラーで本番ビルドを設定する開発スキルです。アプリ、バックエンド、CLI、ライブラリ向けに、ターゲットや形式、最適化、環境別の設定を扱います。
主な機能
- 01ブラウザー、Node.js、Bunのターゲット設定
- 02ESM、CommonJS、IIFE形式の設定
- 03圧縮、コード分割、ソースマップの有効化
- 04環境別ビルドスクリプトの設定
- 05ライブラリの型宣言生成
活用シーン
- 01フロントエンドアプリの本番ビルド設定
- 02Node.jsバックエンドのバンドル設定
- 03ライブラリやCLIの出力構成
- 04開発用と本番用のビルド調整
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ daleseo/ bun-skills --skill bun-buildインストール後、Claude Code で/bun-buildを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/optimization.mdplugins.mdtargets.md詳細
Bun の本番ビルド設定
Bun のネイティブバンドラーを使用して本番ビルドを設定します。webpack や esbuild を使わず、高速で最適化されたバンドルを作成できます。
クイックリファレンス
詳しいパターンについては、以下を参照してください。
- ビルドターゲット:targets.md - ブラウザー、Node.js、ライブラリ、CLI の設定
- 最適化:optimization.md - ツリーシェイキング、コード分割、分析
- プラグイン:plugins.md - カスタムローダーと変換
基本的なワークフロー
1. 前提条件を確認する
# Verify Bun installation
bun --version
# Check project structure
ls -la package.json src/
2. ビルド要件を決定する
ビルドのニーズについてユーザーに確認します。
- アプリケーションの種類:フロントエンド SPA、Node.js バックエンド、CLI ツール、またはライブラリ
- ターゲットプラットフォーム:ブラウザー、Node.js、Bun ランタイム、または Cloudflare Workers
- 出力形式:ESM(最新)、CommonJS(レガシー)、または両方
3. 基本的なビルドスクリプトを作成する
プロジェクトのルートに build.ts を作成します。
#!/usr/bin/env bun
const result = await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
target: 'browser', // or 'node', 'bun'
format: 'esm', // or 'cjs', 'iife'
minify: true,
splitting: true,
sourcemap: 'external',
});
if (!result.success) {
console.error('Build failed');
for (const message of result.logs) {
console.error(message);
}
process.exit(1);
}
console.log('✅ Build successful');
console.log(`📦 ${result.outputs.length} files generated`);
// Show bundle sizes
for (const output of result.outputs) {
const size = (output.size / 1024).toFixed(2);
console.log(` ${output.path} - ${size} KB`);
}
4. ターゲットプラットフォーム向けに設定する
ブラウザー/フロントエンドの場合:
await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist',
target: 'browser',
format: 'esm',
minify: true,
splitting: true,
define: {
'process.env.NODE_ENV': '"production"',
},
loader: {
'.png': 'file',
'.svg': 'dataurl',
'.css': 'css',
},
});
Node.js バックエンドの場合:
await Bun.build({
entrypoints: ['./src/server.ts'],
outdir: './dist',
target: 'node',
format: 'esm',
minify: true,
external: ['*'], // Don't bundle node_modules
});
ライブラリ、CLI ツール、その他のターゲットについては、targets.md を参照してください。
5. 本番環境向けの最適化を追加する
await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
target: 'browser',
// Maximum minification
minify: {
whitespace: true,
identifiers: true,
syntax: true,
},
// Code splitting for optimal caching
splitting: true,
// Content hashing for cache busting
naming: {
entry: '[dir]/[name].[hash].[ext]',
chunk: 'chunks/[name].[hash].[ext]',
asset: 'assets/[name].[hash].[ext]',
},
// Source maps for debugging
sourcemap: 'external',
});
高度な最適化(ツリーシェイキング、バンドル分析、サイズ制限)については、optimization.md を参照してください。
6. 環境ごとのビルドを設定する
build-env.ts を作成します。
#!/usr/bin/env bun
const env = process.env.NODE_ENV || 'development';
const configs = {
development: {
minify: false,
sourcemap: 'inline',
define: {
'process.env.NODE_ENV': '"development"',
'process.env.API_URL': '"http://localhost:3000"',
},
},
production: {
minify: true,
sourcemap: 'external',
define: {
'process.env.NODE_ENV': '"production"',
'process.env.API_URL': '"https://api.example.com"',
},
},
};
const config = configs[env as keyof typeof configs];
const result = await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
target: 'browser',
format: 'esm',
splitting: true,
...config,
});
if (!result.success) {
console.error('❌ Build failed');
process.exit(1);
}
console.log(`✅ ${env} build successful`);
次のコマンドで実行します。
NODE_ENV=production bun run build-env.ts
7. package.json を更新する
ビルドスクリプトを追加します。
{
"scripts": {
"build": "bun run build.ts",
"build:dev": "NODE_ENV=development bun run build-env.ts",
"build:prod": "NODE_ENV=production bun run build-env.ts",
"build:watch": "bun run build.ts --watch",
"clean": "rm -rf dist"
}
}
ライブラリの場合は、以下も追加します。
{
"type": "module",
"main": "./dist/cjs/index.js",
"module": "./dist/esm/index.js",
"types": "./dist/esm/index.d.ts",
"exports": {
".": {
"import": "./dist/esm/index.js",
"require": "./dist/cjs/index.js",
"types": "./dist/esm/index.d.ts"
}
},
"files": ["dist"]
}
8. 型宣言を生成する(ライブラリ)
ライブラリの場合は、TypeScript の型宣言を生成します。
// build-lib-with-types.ts
import { $ } from 'bun';
// Build JavaScript
await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
target: 'node',
format: 'esm',
minify: true,
});
// Generate type declarations
await $`bunx tsc --declaration --emitDeclarationOnly --outDir dist`;
console.log('✅ Built library with type declarations');
ビルドオプションのリファレンス
ターゲット
browser:Web アプリケーション向け(ブラウザーのグローバル変数を含む)node:Node.js アプリケーション向け(Node.js API を前提とする)bun:Bun ランタイム向け(Bun 固有の機能に最適化)
形式
esm:ES Modules(最新、ツリーシェイキング可能)- 推奨cjs:CommonJS(レガシー Node.js)iife:即時実行関数式(ブラウザースクリプト)
ミニファイ
minify: true // Basic minification
minify: { // Granular control
whitespace: true,
identifiers: true,
syntax: true,
}
ソースマップ
external:個別の .map ファイル(本番環境)inline:バンドル内に埋め込み(開発環境)none:ソースマップなし
検証
ビルド後に、以下を実行します。
# 1. Check output directory
ls -lh dist/
# 2. Verify bundle size
du -sh dist/*
# 3. Test bundle
bun run dist/index.js
# 4. Check for errors
echo $? # Should be 0
よく使われるビルドパターン
開発時の監視モード:
import { watch } from 'fs';
async function build() {
await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
minify: false,
});
}
await build();
watch('./src', { recursive: true }, async (event, filename) => {
if (filename?.endsWith('.ts')) {
console.log(`Rebuilding...`);
await build();
}
});
カスタムアセットローダー:
loader: {
'.png': 'file', // Copy file, return path
'.svg': 'dataurl', // Inline as data URL
'.txt': 'text', // Inline as string
'.json': 'json', // Parse and inline
}
カスタムプラグインや高度な変換については、plugins.md を参照してください。
トラブルシューティング
ビルドに失敗する場合:
if (!result.success) {
for (const log of result.logs) {
console.error(log);
}
}
バンドルが大きすぎる場合: 以下については optimization.md を参照してください。
- バンドル分析
- コード分割
- ツリーシェイキング
- サイズ制限
モジュールが見つからない場合:
external の設定を確認します。
external: ['*'] // Exclude all node_modules
external: ['react'] // Exclude specific packages
external: [] // Bundle everything
完了チェックリスト
- ✅ ビルドスクリプトを作成済み
- ✅ ターゲットプラットフォームを設定済み
- ✅ ミニファイを有効化済み
- ✅ ソースマップを設定済み
- ✅ 環境ごとのビルドを設定済み
- ✅ package.json にスクリプトを追加済み
- ✅ ビルドが正常に動作することを確認済み
- ✅ バンドルサイズを確認済み
次のステップ
基本的なビルド設定の後に行うこと:
- 最適化:バンドル分析とサイズ制限を追加する
- CI/CD:パイプラインでビルドを自動化する
- 型チェック:ビルド前の型チェックを追加する
- テスト:ビルド前にテストを実行する
- デプロイ:コンテナ化のために bun-deploy と統合する
詳しい実装については、上記のリンク先のリファレンスファイルを参照してください。