🔨 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 |
node | Node.js 环境 |
bun | Bun 运行时(默认) |
前端打包
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 ARM64darwin-x64- macOS Inteldarwin-arm64- macOS Apple Siliconwindows-x64- Windows 64 位
⚡ 配置选项
| 选项 | 类型 | 说明 |
|---|---|---|
| entrypoints | string[] | 入口文件 |
| outdir | string | 输出目录 |
| target | string | 目标环境 |
| minify | boolean | 压缩代码 |
| splitting | boolean | 代码分割 |
| sourcemap | string | 源码映射 |
| define | object | 全局变量 |
| loader | object | 文件加载器 |
| external | string[] | 外部依赖 |
🔄 文件加载器
typescript
await Bun.build({
entrypoints: ["./src/index.ts"],
outdir: "./dist",
loader: {
".png": "file", // 复制文件,返回路径
".svg": "dataurl", // Base64 内联
".json": "json", // JSON 模块
".txt": "text", // 文本内容
".wasm": "file", // WebAssembly
},
});