--define
标志可以与 bun build
和 bun build --compile
一起使用,将构建时常量注入到您的应用程序中。这对于将元数据(如构建版本、时间戳或配置标志)直接嵌入到已编译的可执行文件中特别有用。
bun build --compile --define BUILD_VERSION='"1.2.3"' --define BUILD_TIME='"2024-01-15T10:30:00Z"' src/index.ts --outfile myapp
为什么使用构建时常量?
构建时常量直接嵌入到您的已编译代码中,使它们
- 零运行时开销 - 无需查找环境变量或读取文件
- 不可变 - 值在编译时已烘焙到二进制文件中
- 可优化 - 死代码消除可以移除未使用的分支
- 安全 - 无需管理外部依赖项或配置文件
这类似于 C/C++ 中的 gcc -D
或 #define
,但适用于 JavaScript/TypeScript。
基本用法
使用 bun build
# Bundle with build-time constants
bun build --define BUILD_VERSION='"1.0.0"' --define NODE_ENV='"production"' src/index.ts --outdir ./dist
使用 bun build --compile
# Compile to executable with build-time constants
bun build --compile --define BUILD_VERSION='"1.0.0"' --define BUILD_TIME='"2024-01-15T10:30:00Z"' src/cli.ts --outfile mycli
JavaScript API
await Bun.build({
entrypoints: ["./src/index.ts"],
outdir: "./dist",
define: {
BUILD_VERSION: '"1.0.0"',
BUILD_TIME: '"2024-01-15T10:30:00Z"',
DEBUG: "false",
},
});
常见用例
版本信息
将版本和构建元数据直接嵌入到您的可执行文件中
// These constants are replaced at build time
declare const BUILD_VERSION: string;
declare const BUILD_TIME: string;
declare const GIT_COMMIT: string;
export function getVersion() {
return {
version: BUILD_VERSION,
buildTime: BUILD_TIME,
commit: GIT_COMMIT,
};
}
bun build --compile \
--define BUILD_VERSION='"1.2.3"' \
--define BUILD_TIME='"2024-01-15T10:30:00Z"' \
--define GIT_COMMIT='"abc123"' \
src/cli.ts --outfile mycli
功能标志
使用构建时常量来启用/禁用功能
// Replaced at build time
declare const ENABLE_ANALYTICS: boolean;
declare const ENABLE_DEBUG: boolean;
function trackEvent(event: string) {
if (ENABLE_ANALYTICS) {
// This entire block is removed if ENABLE_ANALYTICS is false
console.log("Tracking:", event);
}
}
if (ENABLE_DEBUG) {
console.log("Debug mode enabled");
}
# Production build - analytics enabled, debug disabled
bun build --compile --define ENABLE_ANALYTICS=true --define ENABLE_DEBUG=false src/app.ts --outfile app-prod
# Development build - both enabled
bun build --compile --define ENABLE_ANALYTICS=false --define ENABLE_DEBUG=true src/app.ts --outfile app-dev
Configuration
在构建时替换配置对象
declare const CONFIG: {
apiUrl: string;
timeout: number;
retries: number;
};
// CONFIG is replaced with the actual object at build time
const response = await fetch(CONFIG.apiUrl, {
timeout: CONFIG.timeout,
});
bun build --compile --define 'CONFIG={"apiUrl":"https://api.example.com","timeout":5000,"retries":3}' src/app.ts --outfile app
高级模式
特定于环境的构建
为不同环境创建不同的可执行文件
{
"scripts": {
"build:dev": "bun build --compile --define NODE_ENV='\"development\"' --define API_URL='\"https://:3000\"' src/app.ts --outfile app-dev",
"build:staging": "bun build --compile --define NODE_ENV='\"staging\"' --define API_URL='\"https://staging.example.com\"' src/app.ts --outfile app-staging",
"build:prod": "bun build --compile --define NODE_ENV='\"production\"' --define API_URL='\"https://api.example.com\"' src/app.ts --outfile app-prod"
}
}
使用 Shell 命令获取动态值
从 Shell 命令生成构建时常量
# Use git to get current commit and timestamp
bun build --compile \
--define BUILD_VERSION="\"$(git describe --tags --always)\"" \
--define BUILD_TIME="\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"" \
--define GIT_COMMIT="\"$(git rev-parse HEAD)\"" \
src/cli.ts --outfile mycli
构建自动化脚本
创建构建脚本,自动注入构建元数据
// build.ts
import { $ } from "bun";
const version = await $`git describe --tags --always`.text();
const buildTime = new Date().toISOString();
const gitCommit = await $`git rev-parse HEAD`.text();
await Bun.build({
entrypoints: ["./src/cli.ts"],
outdir: "./dist",
define: {
BUILD_VERSION: JSON.stringify(version.trim()),
BUILD_TIME: JSON.stringify(buildTime),
GIT_COMMIT: JSON.stringify(gitCommit.trim()),
},
});
console.log(`Built with version ${version.trim()}`);
重要注意事项
值格式
值必须是有效的 JSON,它将被解析并作为 JavaScript 表达式内联
# ✅ Strings must be JSON-quoted
--define VERSION='"1.0.0"'
# ✅ Numbers are JSON literals
--define PORT=3000
# ✅ Booleans are JSON literals
--define DEBUG=true
# ✅ Objects and arrays (use single quotes to wrap the JSON)
--define 'CONFIG={"host":"localhost","port":3000}'
# ✅ Arrays work too
--define 'FEATURES=["auth","billing","analytics"]'
# ❌ This won't work - missing quotes around string
--define VERSION=1.0.0
属性键
您可以使用属性访问模式作为键,而不仅仅是简单的标识符
# ✅ Replace process.env.NODE_ENV with "production"
--define 'process.env.NODE_ENV="production"'
# ✅ Replace process.env.API_KEY with the actual key
--define 'process.env.API_KEY="abc123"'
# ✅ Replace nested properties
--define 'window.myApp.version="1.0.0"'
# ✅ Replace array access
--define 'process.argv[2]="--production"'
这对于环境变量尤其有用
// Before compilation
if (process.env.NODE_ENV === "production") {
console.log("Production mode");
}
// After compilation with --define 'process.env.NODE_ENV="production"'
if ("production" === "production") {
console.log("Production mode");
}
// After optimization
console.log("Production mode");
TypeScript 声明
对于 TypeScript 项目,声明您的常量以避免类型错误
// types/build-constants.d.ts
declare const BUILD_VERSION: string;
declare const BUILD_TIME: string;
declare const NODE_ENV: "development" | "staging" | "production";
declare const DEBUG: boolean;
跨平台兼容性
在为多个平台构建时,常量的工作方式相同
# Linux
bun build --compile --target=bun-linux-x64 --define PLATFORM='"linux"' src/app.ts --outfile app-linux
# macOS
bun build --compile --target=bun-darwin-x64 --define PLATFORM='"darwin"' src/app.ts --outfile app-macos
# Windows
bun build --compile --target=bun-windows-x64 --define PLATFORM='"windows"' src/app.ts --outfile app-windows.exe
- 在运行时定义常量 - 使用
bun run
配合--define
- 构建可执行文件 -
bun build --compile
的完整指南 - Bundler API - 完整的 Bundler 文档,包括
define
选项