> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# TOML

> 通过运行时 API 和打包器集成使用 Bun 内置的 TOML 文件支持

在 Bun 中，TOML 与 JSON、JSON5 和 YAML 一样是一等公民。您可以：

* 使用 `Bun.TOML.parse` 解析 TOML 字符串
* 在运行时 `import` 和 `require` TOML 文件作为模块（包括热重载和监视模式支持）
* 在前端应用中使用 Bun 的打包器 `import` 和 `require` TOML 文件

***

## 运行时 API

### `Bun.TOML.parse()`

将 TOML 字符串解析为 JavaScript 对象。

```ts theme={null}
import { TOML } from "bun";
const text = `
name = "my-app"
version = "1.0.0"
debug = true

[database]
host = "localhost"
port = 5432

[features]
tags = ["web", "api"]
`;

const data = TOML.parse(text);
console.log(data);
// {
//   name: "my-app",
//   version: "1.0.0",
//   debug: true,
//   database: { host: "localhost", port: 5432 },
//   features: { tags: ["web", "api"] }
// }
```

#### 支持的 TOML 特性

Bun 的 TOML 解析器实现了完整的 [TOML v1.1.0 规范](https://github.com/toml-lang/toml/releases/tag/1.1.0)，并通过了完整的官方 [toml-test](https://github.com/toml-lang/toml-test) 一致性测试套件。

* **字符串**：基本（`"..."`）和字面量（`'...'`），包括多行，所有转义符（`\uHHHH`、`\UHHHHHHHH` 以及 TOML 1.1 的 `\xHH` 和 `\e`）
* **整数**：十进制、十六进制（`0x`）、八进制（`0o`）和二进制（`0b`）。无法无损表示为 JavaScript 数值的整数——超出 ±(2^53 - 1)——会抛出异常
* **浮点数**：包括 `inf` 和 `nan`
* **布尔值**：`true` 和 `false`
* **日期/时间**：偏移日期时间、本地日期时间、本地日期和本地时间，以其源文本字符串形式返回
* **数组**：包括混合类型和嵌套数组
* **表**：标准（`[table]`）和内联（`{ key = "value" }`），包括 TOML 1.1 多行内联表
* **表数组**：`[[array]]`
* **点键**：`a.b.c = "value"`
* **注释**：使用 `#`

```ts theme={null}
const data = Bun.TOML.parse(`
# Application config
title = "My App"

[owner]
name = "John Doe"

[database]
enabled = true
ports = [8000, 8001, 8002]
connection_max = 5000

[servers.alpha]
ip = "10.0.0.1"
role = "frontend"

[servers.beta]
ip = "10.0.0.2"
role = "backend"
`);
```

#### 错误处理

`Bun.TOML.parse()` 在 TOML 无效时抛出 `SyntaxError`：

```ts theme={null}
try {
  Bun.TOML.parse("invalid = = =");
} catch (error) {
  console.error("Failed to parse TOML:", error.message);
  // Failed to parse TOML: TOML Parse error: Expected a value but found '='
}
```

### `Bun.TOML.stringify()`

将 JavaScript 对象序列化为 TOML 文档。标量键在前，然后是 `[table]` 和 `[[array-of-tables]]` 部分：

```ts theme={null}
Bun.TOML.stringify({
  name: "app",
  server: { host: "localhost", port: 8080 },
  points: [{ x: 1 }, { x: 2 }],
});
// name = "app"
//
// [server]
// host = "localhost"
// port = 8080
//
// [[points]]
// x = 1
//
// [[points]]
// x = 2
```

顶层值必须是对象——TOML 文档就是一个表。`Date` 值变成 TOML 偏移日期时间。由于 TOML 无法表示它们，`null` 值、`BigInt` 和循环结构会抛出异常；`undefined`、函数和符号属性会被跳过（在数组内部会抛出异常，因为 TOML 数组不能有空位）。

***

## 模块导入

### ES 模块

直接作为 ES 模块导入 TOML 文件。Bun 解析 TOML 并将其作为默认导出和命名导出暴露：

```toml config.toml theme={null}
[database]
host = "localhost"
port = 5432
name = "myapp"

[redis]
host = "localhost"
port = 6379

[features]
auth = true
rateLimit = true
analytics = false
```

#### 默认导入

```ts app.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import config from "./config.toml";

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

#### 命名导入

您可以将顶层的 TOML 表解构为命名导入：

```ts app.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import { database, redis, features } from "./config.toml";

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

或者组合两者：

```ts app.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import config, { database, features } from "./config.toml";

// 使用完整的配置对象
console.log(config);

// 或使用特定部分
if (features.rateLimit) {
  setupRateLimiting(database);
}
```

#### 导入属性

使用导入属性将任何文件作为 TOML 加载：

```ts app.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import myConfig from "./my.config" with { type: "toml" };
```

### CommonJS

您也可以在 CommonJS 中 `require` TOML 文件：

```ts app.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
const config = require("./config.toml");
console.log(config.database.name); // "myapp"

// 解构也能工作
const { database, redis } = require("./config.toml");
console.log(database.port); // 5432
```

***

## TOML 热重载

当您使用 `bun --hot` 运行应用程序时，Bun 会检测 TOML 文件的更改并重新加载它们，无需重启：

```toml config.toml theme={null}
[server]
port = 3000
host = "localhost"

[features]
debug = true
verbose = false
```

```ts server.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import { server, features } from "./config.toml";

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

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

使用热重载运行：

```bash terminal icon="terminal" theme={null}
bun --hot server.ts
```

***

## 打包器集成

当您使用 Bun 打包时，打包器会在构建时解析导入的 TOML 并将其作为 JavaScript 模块包含：

```bash terminal icon="terminal" theme={null}
bun build app.ts --outdir=dist
```

这意味着：

* 生产环境中零运行时 TOML 解析开销
* 更小的打包体积
* 未使用属性的摇树优化（命名导入）

### 动态导入

您也可以动态导入 TOML 文件：

```ts theme={null}
const config = await import("./config.toml");
```
