mcpField
B
bun-bundler

bun-bundler

github.com/secondsky开发240406 次安装5 周前更新
代码仓库

关于 bun-bundler

这是一份使用 Bun 的 JavaScript 和 TypeScript 打包器的技能指南,涵盖命令行与 JavaScript API。内容包括构建目标、加载器、代码分割、插件和常见错误。

主要功能

  1. 01通过命令行和 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 的打包器是一款快速的 JavaScript/TypeScript 打包器,基于与 Bun 运行时相同的引擎构建。它是一个兼容 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:

  • 使用编译时宏
  • 在构建时生成代码

评论

支持 Markdown