Skip to content

Die --define-Flag kann mit bun build und bun build --compile verwendet werden, um Build-Zeit-Konstanten in Ihre Anwendung zu injizieren. Dies ist besonders nützlich, um Metadaten wie Build-Versionen, Zeitstempel oder Konfigurations-Flags direkt in Ihre kompilierten Executables einzubetten.

sh
bun build --compile --define BUILD_VERSION='"1.2.3"' --define BUILD_TIME='"2024-01-15T10:30:00Z"' src/index.ts --outfile myapp

Warum Build-Zeit-Konstanten verwenden?

Build-Zeit-Konstanten werden direkt in Ihren kompilierten Code eingebettet, was sie:

  • Null Laufzeit-Overhead macht - Keine Umgebungsvariablen-Lookups oder Dateilesungen
  • Unveränderlich - Werte sind zur Compile-Zeit im Binary fest verankert
  • Optimierbar - Dead-Code-Eliminierung kann ungenutzte Zweige entfernen
  • Sicher - Keine externen Abhängigkeiten oder Konfigurationsdateien zu verwalten

Dies ist ähnlich wie gcc -D oder #define in C/C++, aber für JavaScript/TypeScript.


Grundlegende Verwendung

Mit bun build

sh
# Bundle mit Build-Zeit-Konstanten
bun build --define BUILD_VERSION='"1.0.0"' --define NODE_ENV='"production"' src/index.ts --outdir ./dist

Mit bun build --compile

sh
# Zu Executable mit Build-Zeit-Konstanten kompilieren
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",
  },
});

Häufige Anwendungsfälle

Versionsinformationen

Betten Sie Versions- und Build-Metadaten direkt in Ihre Executable ein:

ts
// 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,
  };
}
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

Feature-Flags

Verwenden Sie Build-Zeit-Konstanten, um Features zu aktivieren/deaktivieren:

ts
// 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");
}
sh
# 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

Konfiguration

Ersetzen Sie Konfigurationsobjekte zur Build-Zeit:

ts
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,
});
sh
bun build --compile --define 'CONFIG={"apiUrl":"https://api.example.com","timeout":5000,"retries":3}' src/app.ts --outfile app

Erweiterte Muster

Umgebungsspezifische Builds

Erstellen Sie verschiedene Executables für verschiedene Umgebungen:

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"
  }
}

Shell-Befehle für dynamische Werte verwenden

Generieren Sie Build-Zeit-Konstanten aus Shell-Befehlen:

sh
# 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-Automatisierungsskript

Erstellen Sie ein Build-Skript, das automatisch Build-Metadaten injiziert:

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()}`);

Wichtige Überlegungen

Wertformat

Werte müssen gültiges JSON sein, das als JavaScript-Ausdrücke geparst und inline eingefügt wird:

sh
# ✅ 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

Property-Schlüssel

Sie können Property-Zugriffsmuster als Schlüssel verwenden, nicht nur einfache Bezeichner:

sh
# ✅ 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"'

Dies ist besonders nützlich für Umgebungsvariablen:

ts
// 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-Deklarationen

Für TypeScript-Projekte deklarieren Sie Ihre Konstanten, um Typfehler zu vermeiden:

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;

Plattformübergreifende Kompatibilität

Beim Erstellen für mehrere Plattformen funktionieren Konstanten auf die gleiche Weise:

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

Verwandtes

Bun von www.bunjs.com.cn bearbeitet