Skip to content

Bun unterstützt .yaml- und .yml-Importe nativ.

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

server:
  port: 3000
  timeout: 30

features:
  auth: true
  rateLimit: true

Importieren Sie die Datei wie jede andere Quelldatei.

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

config.database.host; // => "localhost"
config.server.port; // => 3000
config.features.auth; // => true

Sie können auch benannte Importe verwenden, um Top-Level-Properties zu destrukturieren:

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

console.log(database.name); // => "myapp"
console.log(server.timeout); // => 30
console.log(features.rateLimit); // => true

Bun unterstützt auch die Import Attributes-Syntax:

ts
import config from "./config.yaml" with { type: "yaml" };

config.database.port; // => 5432

Verwenden Sie zum Parsen von YAML-Strings zur Laufzeit Bun.YAML.parse():

ts
const yamlString = `
name: John Doe
age: 30
hobbies:
  - reading
  - coding
`;

const data = Bun.YAML.parse(yamlString);
console.log(data.name); // => "John Doe"
console.log(data.hobbies); // => ["reading", "coding"]

TypeScript-Unterstützung

Um TypeScript-Unterstützung für Ihre YAML-Importe hinzuzufügen, erstellen Sie eine Deklarationsdatei mit .d.ts angehängt an den YAML-Dateinamen (z. B. config.yamlconfig.yaml.d.ts);

ts
const contents: {
  database: {
    host: string;
    port: number;
    name: string;
  };
  server: {
    port: number;
    timeout: number;
  };
  features: {
    auth: boolean;
    rateLimit: boolean;
  };
};

export = contents;

Siehe Docs > API > YAML für die vollständige Dokumentation zur YAML-Unterstützung in Bun.

Bun von www.bunjs.com.cn bearbeitet