Skip to content

Bun supporta nativamente gli import .yaml e .yml.

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

server:
  port: 3000
  timeout: 30

features:
  auth: true
  rateLimit: true

Importa il file come qualsiasi altro file sorgente.

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

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

Puoi anche usare import con nome per destrutturare le proprietà di primo livello:

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

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

Bun supporta anche la sintassi Import Attributes:

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

config.database.port; // => 5432

Per parsare stringhe YAML a runtime, usa 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"]

Supporto TypeScript

Per aggiungere supporto TypeScript per i tuoi import YAML, crea un file di dichiarazione con .d.ts aggiunto al nome del file YAML (es. 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;

Vedi Docs > API > YAML per la documentazione completa sul supporto YAML in Bun.

Bun a cura di www.bunjs.com.cn