Skip to content

In Bun ist YAML ein erstklassiger Bürger neben JSON und TOML. Sie können:

  • YAML-Strings mit Bun.YAML.parse parsen
  • YAML-Dateien als Module zur Laufzeit importieren und requireieren (einschließlich Hot-Reloading- und Watch-Mode-Unterstützung)
  • YAML-Dateien in Frontend-Apps über Buns Bundler importieren und requireieren

Konformität

Buns YAML-Parser besteht derzeit über 90 % der offiziellen YAML-Testsuite. Während wir aktiv daran arbeiten, 100 % Konformität zu erreichen, deckt die aktuelle Implementierung die überwiegende Mehrheit der realen Anwendungsfälle ab. Der Parser ist in Zig für optimale Leistung geschrieben und wird kontinuierlich verbessert.


Runtime-API

Bun.YAML.parse()

Parsen Sie einen YAML-String in ein JavaScript-Objekt.

ts
import { YAML } from "bun";
const text = `
name: John Doe
age: 30
email: john@example.com
hobbies:
  - reading
  - coding
  - hiking
`;

const data = YAML.parse(text);
console.log(data);
// {
//   name: "John Doe",
//   age: 30,
//   email: "john@example.com",
//   hobbies: ["reading", "coding", "hiking"]
// }

Multi-Dokument-YAML

Beim Parsen von YAML mit mehreren Dokumenten (getrennt durch ---) gibt Bun.YAML.parse() ein Array zurück:

ts
const multiDoc = `
---
name: Document 1
---
name: Document 2
---
name: Document 3
`;

const docs = Bun.YAML.parse(multiDoc);
console.log(docs);
// [
//   { name: "Document 1" },
//   { name: "Document 2" },
//   { name: "Document 3" }
// ]

Unterstützte YAML-Funktionen

Buns YAML-Parser unterstützt die vollständige YAML 1.2-Spezifikation, einschließlich:

  • Skalare: Strings, Zahlen, Booleans, Null-Werte
  • Kollektionen: Sequenzen (Arrays) und Mappings (Objekte)
  • Anker und Aliase: wiederverwendbare Knoten mit & und *
  • Tags: Typhinweise wie !!str, !!int, !!float, !!bool, !!null
  • Mehrzeilige Strings: Literal (|) und gefaltete (>) Skalare
  • Kommentare: Verwendung von #
  • Direktiven: %YAML und %TAG
ts
const yaml = `
# Employee record
employee: &emp
  name: Jane Smith
  department: Engineering
  skills:
    - JavaScript
    - TypeScript
    - React

manager: *emp  # Reference to employee

config: !!str 123  # Explicit string type

description: |
  This is a multi-line
  literal string that preserves
  line breaks and spacing.

summary: >
  This is a folded string
  that joins lines with spaces
  unless there are blank lines.
`;

const data = Bun.YAML.parse(yaml);

Fehlerbehandlung

Bun.YAML.parse() wirft einen SyntaxError, wenn das YAML ungültig ist:

ts
try {
  Bun.YAML.parse("invalid: yaml: content:");
} catch (error) {
  console.error("Failed to parse YAML:", error.message);
}

Modul-Import

ES-Module

Sie können YAML-Dateien direkt als ES-Module importieren. Der YAML-Inhalt wird geparst und sowohl als Standard- als auch als benannte Exporte verfügbar gemacht:

yaml
database:
  host: localhost
  port: 5432
  name: myapp

redis:
  host: localhost
  port: 6379

features:
  auth: true
  rateLimit: true
  analytics: false

Standard-Import

ts
import config from "./config.yaml";

console.log(config.database.host); // "localhost"
console.log(config.redis.port); // 6379

Benannte Importe

Sie können YAML-Eigenschaften der obersten Ebene als benannte Importe destrukturieren:

ts
import { database, redis, features } from "./config.yaml";

console.log(database.host); // "localhost"
console.log(redis.port); // 6379
console.log(features.auth); // true

Oder kombinieren Sie beides:

ts
import config, { database, features } from "./config.yaml";

// Verwenden Sie das gesamte Konfigurationsobjekt
console.log(config);

// Oder verwenden Sie bestimmte Teile
if (features.rateLimit) {
  setupRateLimiting(database);
}

CommonJS

YAML-Dateien können auch in CommonJS erforderlich werden:

ts
const config = require("./config.yaml");
console.log(config.database.name); // "myapp"

// Destrukturierung funktioniert ebenfalls
const { database, redis } = require("./config.yaml");
console.log(database.port); // 5432

Hot Reloading mit YAML

Eine der leistungsstärksten Funktionen von Buns YAML-Unterstützung ist das Hot Reloading. Wenn Sie Ihre Anwendung mit bun --hot ausführen, werden Änderungen an YAML-Dateien automatisch erkannt und neu geladen, ohne Verbindungen zu schließen.

Konfigurations-Hot-Reloading

yaml
server:
  port: 3000
  host: localhost

features:
  debug: true
  verbose: false
ts
import { server, features } from "./config.yaml";

console.log(`Starting server on ${server.host}:${server.port}`);

if (features.debug) {
  console.log("Debug mode enabled");
}

// Ihr Server-Code hier
Bun.serve({
  port: server.port,
  hostname: server.host,
  fetch(req) {
    if (features.verbose) {
      console.log(`${req.method} ${req.url}`);
    }
    return new Response("Hello World");
  },
});

Mit Hot Reloading ausführen:

bash
bun --hot server.ts

Wenn Sie nun config.yaml ändern, werden die Änderungen sofort in Ihrer laufenden Anwendung widerspiegelt. Dies ist perfekt für:

  • Anpassen der Konfiguration während der Entwicklung
  • Testen verschiedener Einstellungen ohne Neustarts
  • Live-Debugging mit Konfigurationsänderungen
  • Feature-Flag-Umschaltung

Konfigurationsverwaltung

Umgebungsbasierte Konfiguration

YAML eignet sich hervorragend für die Verwaltung von Konfigurationen über verschiedene Umgebungen hinweg:

yaml
defaults: &defaults
  timeout: 5000
  retries: 3
  cache:
    enabled: true
    ttl: 3600

development:
  <<: *defaults
  api:
    url: http://localhost:4000
    key: dev_key_12345
  logging:
    level: debug
    pretty: true

staging:
  <<: *defaults
  api:
    url: https://staging-api.example.com
    key: ${STAGING_API_KEY}
  logging:
    level: info
    pretty: false

production:
  <<: *defaults
  api:
    url: https://api.example.com
    key: ${PROD_API_KEY}
  cache:
    enabled: true
    ttl: 86400
  logging:
    level: error
    pretty: false
ts
import configs from "./config.yaml";

const env = process.env.NODE_ENV || "development";
const config = configs[env];

// Umgebungsvariablen in YAML-Werten können interpoliert werden
function interpolateEnvVars(obj: any): any {
  if (typeof obj === "string") {
    return obj.replace(/\${(\w+)}/g, (_, key) => process.env[key] || "");
  }
  if (typeof obj === "object") {
    for (const key in obj) {
      obj[key] = interpolateEnvVars(obj[key]);
    }
  }
  return obj;
}

export default interpolateEnvVars(config);

Feature-Flags-Konfiguration

yaml
features:
  newDashboard:
    enabled: true
    rolloutPercentage: 50
    allowedUsers:
      - admin@example.com
      - beta@example.com

  experimentalAPI:
    enabled: false
    endpoints:
      - /api/v2/experimental
      - /api/v2/beta

  darkMode:
    enabled: true
    default: auto # auto, light, dark
ts
import { features } from "./features.yaml";

export function isFeatureEnabled(featureName: string, userEmail?: string): boolean {
  const feature = features[featureName];

  if (!feature?.enabled) {
    return false;
  }

  // Rollout-Prozentsatz überprüfen
  if (feature.rolloutPercentage < 100) {
    const hash = hashCode(userEmail || "anonymous");
    if (hash % 100 >= feature.rolloutPercentage) {
      return false;
    }
  }

  // Erlaubte Benutzer überprüfen
  if (feature.allowedUsers && userEmail) {
    return feature.allowedUsers.includes(userEmail);
  }

  return true;
}

// Mit Hot Reloading verwenden, um Features in Echtzeit umzuschalten
if (isFeatureEnabled("newDashboard", user.email)) {
  renderNewDashboard();
} else {
  renderLegacyDashboard();
}

Datenbank-Konfiguration

yaml
connections:
  primary:
    type: postgres
    host: ${DB_HOST:-localhost}
    port: ${DB_PORT:-5432}
    database: ${DB_NAME:-myapp}
    username: ${DB_USER:-postgres}
    password: ${DB_PASS}
    pool:
      min: 2
      max: 10
      idleTimeout: 30000

  cache:
    type: redis
    host: ${REDIS_HOST:-localhost}
    port: ${REDIS_PORT:-6379}
    password: ${REDIS_PASS}
    db: 0

  analytics:
    type: clickhouse
    host: ${ANALYTICS_HOST:-localhost}
    port: 8123
    database: analytics

migrations:
  autoRun: ${AUTO_MIGRATE:-false}
  directory: ./migrations

seeds:
  enabled: ${SEED_DB:-false}
  directory: ./seeds
ts
import { connections, migrations } from "./database.yaml";
import { createConnection } from "./database-driver";

// Umgebungsvariablen mit Standardwerten parsen
function parseConfig(config: any) {
  return JSON.parse(
    JSON.stringify(config).replace(
      /\${([^:-]+)(?::([^}]+))?}/g,
      (_, key, defaultValue) => process.env[key] || defaultValue || "",
    ),
  );
}

const dbConfig = parseConfig(connections);

export const db = await createConnection(dbConfig.primary);
export const cache = await createConnection(dbConfig.cache);
export const analytics = await createConnection(dbConfig.analytics);

// Migrationen automatisch ausführen, wenn konfiguriert
if (parseConfig(migrations).autoRun === "true") {
  await runMigrations(db, migrations.directory);
}

Bundler-Integration

Wenn Sie YAML-Dateien in Ihrer Anwendung importieren und mit Bun bündeln, wird das YAML zur Build-Zeit geparst und als JavaScript-Modul eingefügt:

bash
bun build app.ts --outdir=dist

Das bedeutet:

  • Null Runtime-YAML-Parsing-Overhead in der Produktion
  • Kleinere Bundle-Größen
  • Tree-Shaking-Unterstützung für ungenutzte Konfiguration (benannte Importe)

Dynamische Importe

YAML-Dateien können dynamisch importiert werden, nützlich für das bedarfsgerechte Laden von Konfigurationen:

ts
const env = process.env.NODE_ENV || "development";
const config = await import(`./configs/${env}.yaml`);

// Benutzerspezifische Einstellungen laden
async function loadUserSettings(userId: string) {
  try {
    const settings = await import(`./users/${userId}/settings.yaml`);
    return settings.default;
  } catch {
    return await import("./users/default-settings.yaml");
  }
}

Bun von www.bunjs.com.cn bearbeitet