Bun 打包插件 #

概述 #

Bun 打包器支持插件系统,可以自定义文件加载、转换和处理逻辑。

插件结构 #

typescript
interface BunPlugin {
  name: string;
  setup(build: PluginBuilder): void;
}

interface PluginBuilder {
  onResolve(options: OnResolveOptions, callback: OnResolveCallback): void;
  onLoad(options: OnLoadOptions, callback: OnLoadCallback): void;
}

基本插件 #

typescript
const myPlugin: BunPlugin = {
  name: "my-plugin",
  setup(build) {
    build.onLoad({ filter: /\.txt$/ }, async (args) => {
      const content = await Bun.file(args.path).text();
      return {
        contents: `export default ${JSON.stringify(content)}`,
        loader: "js",
      };
    });
  },
};

// 使用插件
await build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  plugins: [myPlugin],
});

常用插件示例 #

JSON 插件 #

typescript
const jsonPlugin: BunPlugin = {
  name: "json-plugin",
  setup(build) {
    build.onLoad({ filter: /\.json$/ }, async (args) => {
      const content = await Bun.file(args.path).text();
      return {
        contents: `export default ${content}`,
        loader: "js",
      };
    });
  },
};

环境变量插件 #

typescript
const envPlugin: BunPlugin = {
  name: "env-plugin",
  setup(build) {
    build.onResolve({ filter: /^env$/ }, (args) => {
      return { path: args.path, namespace: "env" };
    });

    build.onLoad({ filter: /.*/, namespace: "env" }, () => {
      const env = process.env;
      return {
        contents: `export default ${JSON.stringify(env)}`,
        loader: "js",
      };
    });
  },
};

虚拟模块插件 #

typescript
const virtualPlugin: BunPlugin = {
  name: "virtual-plugin",
  setup(build) {
    build.onResolve({ filter: /^virtual:/ }, (args) => {
      return { path: args.path.slice(8), namespace: "virtual" };
    });

    build.onLoad({ filter: /.*/, namespace: "virtual" }, (args) => {
      return {
        contents: `export const name = "${args.path}";`,
        loader: "js",
      };
    });
  },
};

使用插件 #

命令行 #

bash
bun build ./src/index.ts --outdir ./dist --plugin ./plugins/my-plugin.ts

编程式 #

typescript
import { build } from "bun";
import { myPlugin } from "./plugins/my-plugin";

await build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  plugins: [myPlugin],
});

下一步 #

现在你已经了解了 Bun 打包插件,接下来学习 测试运行器 了解 Bun 的测试功能。

最后更新:2026-03-29