--define 플래그는 bun build 와 bun build --compile 와 함께 사용하여 애플리케이션에 빌드타임 상수를 주입할 수 있습니다. 이는 빌드 버전, 타임스탬프 또는 구성 플래그와 같은 메타데이터를 컴파일된 실행 파일에 직접 임베딩할 때 특히 유용합니다.
sh
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 사용
sh
# 빌드타임 상수와 함께 번들링
bun build --define BUILD_VERSION='"1.0.0"' --define NODE_ENV='"production"' src/index.ts --outdir ./distbun build --compile 사용
sh
# 빌드타임 상수와 함께 실행 파일로 컴파일
bun build --compile --define BUILD_VERSION='"1.0.0"' --define BUILD_TIME='"2024-01-15T10:30:00Z"' src/cli.ts --outfile mycliJavaScript API
ts
await Bun.build({
entrypoints: ["./src/index.ts"],
outdir: "./dist",
define: {
BUILD_VERSION: '"1.0.0"',
BUILD_TIME: '"2024-01-15T10:30:00Z"',
DEBUG: "false",
},
});일반적인 사용 사례
버전 정보
버전 및 빌드 메타데이터를 실행 파일에 직접 임베딩하세요.
ts
// 이 상수들은 빌드 시점에 대체됩니다
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,
};
}sh
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기능 플래그
빌드타임 상수를 사용하여 기능을 활성화/비활성화하세요.
ts
// 빌드 시점에 대체됨
declare const ENABLE_ANALYTICS: boolean;
declare const ENABLE_DEBUG: boolean;
function trackEvent(event: string) {
if (ENABLE_ANALYTICS) {
// ENABLE_ANALYTICS 가 false 면 이 전체 블록이 제거됨
console.log("Tracking:", event);
}
}
if (ENABLE_DEBUG) {
console.log("Debug mode enabled");
}sh
# 프로덕션 빌드 - 분석 활성화, 디버그 비활성화
bun build --compile --define ENABLE_ANALYTICS=true --define ENABLE_DEBUG=false src/app.ts --outfile app-prod
# 개발 빌드 - 둘 다 활성화
bun build --compile --define ENABLE_ANALYTICS=false --define ENABLE_DEBUG=true src/app.ts --outfile app-dev구성
빌드 시점에 구성 객체를 대체하세요.
ts
declare const CONFIG: {
apiUrl: string;
timeout: number;
retries: number;
};
// CONFIG 는 빌드 시점에 실제 객체로 대체됨
const response = await fetch(CONFIG.apiUrl, {
timeout: CONFIG.timeout,
});sh
bun build --compile --define 'CONFIG={"apiUrl":"https://api.example.com","timeout":5000,"retries":3}' src/app.ts --outfile app고급 패턴
환경별 빌드
다양한 환경에 대해 다른 실행 파일을 만드세요.
json
{
"scripts": {
"build:dev": "bun build --compile --define NODE_ENV='\"development\"' --define API_URL='\"http://localhost: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"
}
}동적 값을 위한 셸 명령 사용
셸 명령에서 빌드타임 상수를 생성하세요.
sh
# git 을 사용하여 현재 커밋과 타임스탬프 가져오기
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빌드 자동화 스크립트
빌드 메타데이터를 자동으로 주입하는 빌드 스크립트를 만드세요.
ts
// 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()}`);중요한 고려 사항
값 형식
값은 JavaScript 표현식으로 구문 분석되고 인라인될 유효한 JSON 이어야 합니다.
sh
# ✅ 문자열은 JSON 따옴표로 감싸야 함
--define VERSION='"1.0.0"'
# ✅ 숫자는 JSON 리터럴
--define PORT=3000
# ✅ 불리언은 JSON 리터럴
--define DEBUG=true
# ✅ 객체와 배열 (JSON 을 감싸려면 단일 따옴표 사용)
--define 'CONFIG={"host":"localhost","port":3000}'
# ✅ 배열도 작동
--define 'FEATURES=["auth","billing","analytics"]'
# ❌ 작동하지 않음 - 문자열 주위에 따옴표 누락
--define VERSION=1.0.0속성 키
단순 식별자가 아닌 속성 액세스 패턴을 키로 사용할 수 있습니다.
sh
# ✅ process.env.NODE_ENV 를 "production" 으로 대체
--define 'process.env.NODE_ENV="production"'
# ✅ process.env.API_KEY 를 실제 키로 대체
--define 'process.env.API_KEY="abc123"'
# ✅ 중첩 속성 대체
--define 'window.myApp.version="1.0.0"'
# ✅ 배열 액세스 대체
--define 'process.argv[2]="--production"'이는 환경 변수에 특히 유용합니다.
ts
// 컴파일 전
if (process.env.NODE_ENV === "production") {
console.log("Production mode");
}
// --define 'process.env.NODE_ENV="production"' 로 컴파일 후
if ("production" === "production") {
console.log("Production mode");
}
// 최적화 후
console.log("Production mode");TypeScript 선언
TypeScript 프로젝트의 경우 타입 오류를 피하기 위해 상수를 선언하세요.
ts
// 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;크로스플랫폼 호환성
여러 플랫폼을 위해 빌드할 때 상수는 동일한 방식으로 작동합니다.
sh
# 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에 대한 완전한 가이드 - 번들러 API -
define옵션을 포함한 전체 번들러 문서