Skip to content

--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 ./dist

bun build --compile と一緒に使用

sh
# ビルド時定数を使用して実行ファイルにコンパイル
bun build --compile --define BUILD_VERSION='"1.0.0"' --define BUILD_TIME='"2024-01-15T10:30:00Z"' src/cli.ts --outfile mycli

JavaScript 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 by www.bunjs.com.cn 編集