bun-build

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Bun Production Build Configuration

Bun 生产环境构建配置

Set up production builds using Bun's native bundler - fast, optimized bundle creation without webpack or esbuild.
使用Bun的原生打包器搭建生产环境构建流程——无需依赖webpack或esbuild,即可快速创建经过优化的打包文件。

Quick Reference

快速参考

For detailed patterns, see:
  • Build Targets: targets.md - Browser, Node.js, library, CLI configurations
  • Optimization: optimization.md - Tree shaking, code splitting, analysis
  • Plugins: plugins.md - Custom loaders and transformations
如需详细配置模式,请查看:
  • 构建目标targets.md - 浏览器、Node.js、库、CLI工具的配置说明
  • 优化配置optimization.md - 摇树优化、代码分割、打包分析
  • 插件plugins.md - 自定义加载器与转换规则

Core Workflow

核心工作流程

1. Check Prerequisites

1. 检查前置条件

bash
undefined
bash
undefined

Verify Bun installation

验证Bun是否安装

bun --version
bun --version

Check project structure

检查项目结构

ls -la package.json src/
undefined
ls -la package.json src/
undefined

2. Determine Build Requirements

2. 确定构建需求

Ask the user about their build needs:
  • Application Type: Frontend SPA, Node.js backend, CLI tool, or library
  • Target Platform: Browser, Node.js, Bun runtime, or Cloudflare Workers
  • Output Format: ESM (modern), CommonJS (legacy), or both
询问用户的构建需求:
  • 应用类型:前端SPA、Node.js后端、CLI工具或类库
  • 目标平台:浏览器、Node.js、Bun运行时或Cloudflare Workers
  • 输出格式:ESM(现代)、CommonJS(兼容旧版)或同时输出两种格式

3. Create Basic Build Script

3. 创建基础构建脚本

Create
build.ts
in project root:
typescript
#!/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`);
}
在项目根目录创建
build.ts
文件:
typescript
#!/usr/bin/env bun

const result = await Bun.build({
  entrypoints: ['./src/index.ts'],
  outdir: './dist',
  target: 'browser', // 或 'node', 'bun'
  format: 'esm', // 或 'cjs', 'iife'
  minify: true,
  splitting: true,
  sourcemap: 'external',
});

if (!result.success) {
  console.error('构建失败');
  for (const message of result.logs) {
    console.error(message);
  }
  process.exit(1);
}

console.log('✅ 构建成功');
console.log(`📦 生成了 ${result.outputs.length} 个文件`);

// 显示打包文件大小
for (const output of result.outputs) {
  const size = (output.size / 1024).toFixed(2);
  console.log(`  ${output.path} - ${size} KB`);
}

4. Configure for Target Platform

4. 针对目标平台配置

For Browser/Frontend:
typescript
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',
  },
});
For Node.js Backend:
typescript
await Bun.build({
  entrypoints: ['./src/server.ts'],
  outdir: './dist',
  target: 'node',
  format: 'esm',
  minify: true,
  external: ['*'], // Don't bundle node_modules
});
For libraries, CLI tools, and other targets, see targets.md.
浏览器/前端项目:
typescript
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后端项目:
typescript
await Bun.build({
  entrypoints: ['./src/server.ts'],
  outdir: './dist',
  target: 'node',
  format: 'esm',
  minify: true,
  external: ['*'], // 不打包node_modules中的依赖
});
类库、CLI工具及其他目标平台的配置,请查看targets.md

5. Add Production Optimizations

5. 添加生产环境优化配置

typescript
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',
});
For advanced optimizations (tree shaking, bundle analysis, size limits), see optimization.md.
typescript
await Bun.build({
  entrypoints: ['./src/index.ts'],
  outdir: './dist',
  target: 'browser',

  // 最大化压缩
  minify: {
    whitespace: true,
    identifiers: true,
    syntax: true,
  },

  // 代码分割以优化缓存
  splitting: true,

  // 内容哈希以实现缓存击穿
  naming: {
    entry: '[dir]/[name].[hash].[ext]',
    chunk: 'chunks/[name].[hash].[ext]',
    asset: 'assets/[name].[hash].[ext]',
  },

  // 用于调试的源映射
  sourcemap: 'external',
});
如需高级优化配置(摇树优化、打包分析、体积限制等),请查看optimization.md

6. Environment-Specific Builds

6. 多环境构建配置

Create
build-env.ts
:
typescript
#!/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`);
Run with:
bash
NODE_ENV=production bun run build-env.ts
创建
build-env.ts
文件:
typescript
#!/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('❌ 构建失败');
  process.exit(1);
}

console.log(`${env} 环境构建成功`);
运行命令:
bash
NODE_ENV=production bun run build-env.ts

7. Update package.json

7. 更新package.json

Add build scripts:
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"
  }
}
For libraries, also add:
json
{
  "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"]
}
添加构建脚本:
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"
  }
}
类库项目还需添加:
json
{
  "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. Generate Type Declarations (Libraries)

8. 生成TypeScript类型声明(类库项目)

For libraries, generate TypeScript declarations:
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');
对于类库项目,生成TypeScript类型声明:
typescript
// build-lib-with-types.ts
import { $ } from 'bun';

// 构建JavaScript代码
await Bun.build({
  entrypoints: ['./src/index.ts'],
  outdir: './dist',
  target: 'node',
  format: 'esm',
  minify: true,
});

// 生成类型声明
await $`bunx tsc --declaration --emitDeclarationOnly --outDir dist`;

console.log('✅ 已构建包含类型声明的类库');

Build Options Reference

构建选项参考

Target

Target(目标平台)

  • browser
    : For web applications (includes browser globals)
  • node
    : For Node.js applications (assumes Node.js APIs)
  • bun
    : For Bun runtime (optimized for Bun-specific features)
  • browser
    :适用于Web应用(包含浏览器全局变量)
  • node
    :适用于Node.js应用(假设依赖Node.js API)
  • bun
    :适用于Bun运行时(针对Bun专属特性优化)

Format

Format(输出格式)

  • esm
    : ES Modules (modern, tree-shakeable) - Recommended
  • cjs
    : CommonJS (legacy Node.js)
  • iife
    : Immediately Invoked Function Expression (browser scripts)
  • esm
    :ES Modules(现代格式,支持摇树优化)- 推荐使用
  • cjs
    :CommonJS(旧版Node.js兼容格式)
  • iife
    :立即执行函数表达式(浏览器脚本格式)

Minification

Minification(代码压缩)

typescript
minify: true                  // Basic minification
minify: {                     // Granular control
  whitespace: true,
  identifiers: true,
  syntax: true,
}
typescript
minify: true                  // 基础压缩
minify: {                     // 精细化控制
  whitespace: true,
  identifiers: true,
  syntax: true,
}

Source Maps

Source Maps(源映射)

  • external
    : Separate .map files (production)
  • inline
    : Inline in bundle (development)
  • none
    : No source maps
  • external
    :生成独立的.map文件(生产环境推荐)
  • inline
    :内联到打包文件中(开发环境推荐)
  • none
    :不生成源映射

Verification

验证构建结果

After building:
bash
undefined
构建完成后:
bash
undefined

1. Check output directory

1. 检查输出目录

ls -lh dist/
ls -lh dist/

2. Verify bundle size

2. 验证打包文件体积

du -sh dist/*
du -sh dist/*

3. Test bundle

3. 测试打包文件

bun run dist/index.js
bun run dist/index.js

4. Check for errors

4. 检查是否有错误

echo $? # Should be 0
undefined
echo $? # 结果应为0表示成功
undefined

Common Build Patterns

常见构建模式

Watch mode for development:
typescript
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();
  }
});
Custom asset loaders:
typescript
loader: {
  '.png': 'file',     // Copy file, return path
  '.svg': 'dataurl',  // Inline as data URL
  '.txt': 'text',     // Inline as string
  '.json': 'json',    // Parse and inline
}
For custom plugins and advanced transformations, see plugins.md.
开发环境监听模式:
typescript
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(`正在重新构建...`);
    await build();
  }
});
自定义资源加载器:
typescript
loader: {
  '.png': 'file',     // 复制文件,返回路径
  '.svg': 'dataurl',  // 内联为Data URL
  '.txt': 'text',     // 内联为字符串
  '.json': 'json',    // 解析并内联
}
自定义插件与高级转换的配置,请查看plugins.md

Troubleshooting

故障排查

Build fails:
typescript
if (!result.success) {
  for (const log of result.logs) {
    console.error(log);
  }
}
Bundle too large: See optimization.md for:
  • Bundle analysis
  • Code splitting
  • Tree shaking
  • Size limits
Module not found: Check
external
configuration:
typescript
external: ['*']         // Exclude all node_modules
external: ['react']     // Exclude specific packages
external: []            // Bundle everything
构建失败:
typescript
if (!result.success) {
  for (const log of result.logs) {
    console.error(log);
  }
}
打包文件体积过大: 查看optimization.md获取以下方案:
  • 打包分析
  • 代码分割
  • 摇树优化
  • 体积限制
模块未找到: 检查
external
配置:
typescript
external: ['*']         // 排除所有node_modules依赖
external: ['react']     // 排除特定包
external: []            // 打包所有依赖

Completion Checklist

完成检查清单

  • ✅ Build script created
  • ✅ Target platform configured
  • ✅ Minification enabled
  • ✅ Source maps configured
  • ✅ Environment-specific builds set up
  • ✅ Package.json scripts added
  • ✅ Build tested successfully
  • ✅ Bundle size verified
  • ✅ 已创建构建脚本
  • ✅ 已配置目标平台
  • ✅ 已启用代码压缩
  • ✅ 已配置源映射
  • ✅ 已设置多环境构建
  • ✅ 已添加package.json脚本
  • ✅ 已成功测试构建
  • ✅ 已验证打包文件体积

Next Steps

后续步骤

After basic build setup:
  1. Optimization: Add bundle analysis and size limits
  2. CI/CD: Automate builds in your pipeline
  3. Type Checking: Add pre-build type checking
  4. Testing: Run tests before building
  5. Deployment: Integrate with bun-deploy for containerization
For detailed implementations, see the reference files linked above.
完成基础构建配置后:
  1. 优化:添加打包分析与体积限制
  2. CI/CD:在流水线中自动化构建流程
  3. 类型检查:添加构建前的类型检查
  4. 测试:构建前运行测试用例
  5. 部署:与bun-deploy集成实现容器化部署
如需详细实现方案,请查看上方链接的参考文档。