mcpField
B
bun-bundler

bun-bundler

github.com/secondsky開発240406 回インストール5 週間前に更新
リポジトリ

bun-bundler について

Bun の JavaScript/TypeScript バンドラーを CLI と JavaScript API で使うためのスキルガイドです。ビルド対象、ローダー、コード分割、プラグイン、一般的なエラーを扱います。

主な機能

  1. 01CLI と JavaScript API によるビルド
  2. 02ブラウザー、Bun、Node 向けのビルド
  3. 03コード分割と圧縮
  4. 04組み込みローダーとカスタムローダー
  5. 05プラグインとビルドオプションの解説

活用シーン

  1. 01本番環境向けに TypeScript アプリをバンドル
  2. 02複数のエントリーポイントをビルド
  3. 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単一ファイルとして出力
--targetbrowser、bun、node
--formatesm、cjs、iife
--minify圧縮を有効化
--minify-whitespace空白のみを圧縮
--minify-identifiers識別子のみを圧縮
--minify-syntax構文のみを圧縮
--splittingコード分割を有効化
--sourcemapnone、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、.cjsJavaScript
jsx.jsxJavaScript
ts.ts、.mts、.ctsJavaScript
tsx.tsxJavaScript
json.jsonJavaScript
toml.tomlJavaScript
text-文字列のエクスポート
file-ファイルパスのエクスポート
base64-Base64 文字列
dataurl-Data URL
css.cssCSS ファイル

カスタムローダー:

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 を読み込みます:

  • コンパイル時マクロを使用する場合
  • ビルド時にコードを生成する場合

コメント