🔨 Bun.build

typescript
await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  target: "browser", // browser | node | bun
  minify: true,
  splitting: true,
  sourcemap: "external",
});

🎯 打包目标

target说明
browser浏览器环境,支持 ESM
nodeNode.js 环境
bunBun 运行时(默认)

前端打包

typescript
await Bun.build({
  entrypoints: ["./src/App.tsx"],
  outdir: "./public/dist",
  target: "browser",
  define: {
    "process.env.NODE_ENV": JSON.stringify("production"),
  },
  loader: {
    ".svg": "file",
    ".png": "dataurl",
  },
});

📦 编译可执行文件

将 TypeScript/JavaScript 编译为独立可执行文件。

bash
# 当前平台
bun build ./src/cli.ts --compile --outfile=mycli

# 运行
./mycli

# 跨平台编译
bun build ./src/cli.ts --compile --target=linux-x64 --outfile=mycli-linux
bun build ./src/cli.ts --compile --target=darwin-arm64 --outfile=mycli-mac
bun build ./src/cli.ts --compile --target=windows-x64 --outfile=mycli.exe

支持的目标平台

  • linux-x64 - Linux 64 位
  • linux-arm64 - Linux ARM64
  • darwin-x64 - macOS Intel
  • darwin-arm64 - macOS Apple Silicon
  • windows-x64 - Windows 64 位

⚡ 配置选项

选项类型说明
entrypointsstring[]入口文件
outdirstring输出目录
targetstring目标环境
minifyboolean压缩代码
splittingboolean代码分割
sourcemapstring源码映射
defineobject全局变量
loaderobject文件加载器
externalstring[]外部依赖

🔄 文件加载器

typescript
await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  loader: {
    ".png": "file",      // 复制文件,返回路径
    ".svg": "dataurl",   // Base64 内联
    ".json": "json",     // JSON 模块
    ".txt": "text",      // 文本内容
    ".wasm": "file",     // WebAssembly
  },
});