关于 bun-bundler
这是一份使用 Bun 的 JavaScript 和 TypeScript 打包器的技能指南,涵盖命令行与 JavaScript API。内容包括构建目标、加载器、代码分割、插件和常见错误。
主要功能
- 01通过命令行和 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 的打包器是一款快速的 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 | 输出为单个文件 |
--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