Skip to content

Bun soporta nativamente las importaciones de .yaml y .yml.

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

server:
  port: 3000
  timeout: 30

features:
  auth: true
  rateLimit: true

Importa el archivo como cualquier otro archivo de código fuente.

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

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

También puedes usar importaciones con nombre para desestructurar propiedades de nivel superior:

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

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

Bun también soporta la sintaxis de Atributos de Importación:

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

config.database.port; // => 5432

Para analizar cadenas YAML en tiempo de ejecución, 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"]

Soporte de TypeScript

Para agregar soporte de TypeScript para tus importaciones YAML, crea un archivo de declaración con .d.ts añadido al nombre del archivo YAML (por ejemplo, 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;

Consulta Documentación > API > YAML para la documentación completa sobre el soporte de YAML en Bun.

Bun por www.bunjs.com.cn editar