关于 bun-build
bun-build 是一项使用 Bun 原生打包器配置生产构建的开发技能,面向需要为应用、后端、CLI 或库设置构建流程的开发者。内容涵盖目标平台、输出格式、优化和环境配置。
主要功能
- 01配置浏览器、Node.js 和 Bun 构建目标
- 02设置 ESM、CommonJS 和 IIFE 格式
- 03启用压缩、代码拆分与 source map
- 04配置环境专用构建脚本
- 05为库生成类型声明
适用场景
- 01为前端应用配置生产构建
- 02设置 Node.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 - Tree shaking、代码拆分、分析
- 插件: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',
});
如需高级优化(Tree shaking、打包分析、大小限制),请参阅 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');
构建选项参考
Target
browser:用于 Web 应用(包含浏览器全局对象)node:用于 Node.js 应用(默认使用 Node.js API)bun:用于 Bun 运行时(针对 Bun 特有功能进行优化)
Format
esm:ES Modules(现代、可进行 Tree shaking)- 推荐cjs:CommonJS(传统 Node.js)iife:立即调用函数表达式(浏览器脚本)
Minification
minify: true // Basic minification
minify: { // Granular control
whitespace: true,
identifiers: true,
syntax: true,
}
Source Maps
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,了解:
- 打包分析
- 代码拆分
- Tree shaking
- 大小限制
找不到模块:
检查 external 配置:
external: ['*'] // Exclude all node_modules
external: ['react'] // Exclude specific packages
external: [] // Bundle everything
完成检查清单
- ✅ 已创建构建脚本
- ✅ 已配置目标平台
- ✅ 已启用压缩
- ✅ 已配置源映射
- ✅ 已设置特定环境的构建
- ✅ 已添加 package.json 脚本
- ✅ 已成功测试构建
- ✅ 已验证打包文件大小
后续步骤
完成基本构建设置后:
- 优化:添加打包分析和大小限制
- CI/CD:在流水线中自动执行构建
- 类型检查:添加构建前类型检查
- 测试:在构建前运行测试
- 部署:集成 bun-deploy,以便进行容器化
如需查看详细实现,请参阅上文链接的参考文件。
评论
支持 Markdown