# @decimalturn/toml-patch 中文文档

规范地址：https://npmcn.com/package/%40decimalturn/toml-patch/

版本：3\.3\.2
npm 元数据更新时间：2026-10-31T21:49:28.461Z
中文译文更新时间：2026-10-31T22:49:51.796Z
软件包许可：MIT

本文由上游 README 机器翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40decimalturn/toml-patch
原文对照：https://npmcn.com/package/%40decimalturn/toml-patch/?lang=original
项目主页：https://github.com/DecimalTurn/toml-patch
源码仓库：https://github.com/DecimalTurn/toml-patch

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：216 kB，5 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=16
- 运行依赖：0 个
- 首次发布：2025-04-12T04:14:49.886Z
- 最新版本发布：2026-10-31T21:49:28.167Z
- 已发布版本数：58（近 12 个月 49 个）

## 中文简介

修补、解析和字符串化TOML，同时保留注释、空白和格式。

## 安装

```sh
npm install @decimalturn/toml-patch
```

也可以使用：`pnpm add @decimalturn/toml-patch`、`yarn add @decimalturn/toml-patch`、`bun add @decimalturn/toml-patch`

## README

![toml-patch logo](https://npmcn.com/package/%40decimalturn/toml-patch/assets/toml-patch-logo.png)

# toml-patch

[![NPM Version](https://img.shields.io/npm/v/%40decimalturn%2Ftoml-patch?logo=npm&logoColor=white&labelColor=red&color=blue)](https://www.npmjs.com/package/@decimalturn/toml-patch) [![JSR Version](https://img.shields.io/jsr/v/%40decimalturn/toml-patch?logo=jsr&color=blue)](https://jsr.io/@decimalturn/toml-patch) [![GitHub branch status](https://img.shields.io/github/check-runs/DecimalTurn/toml-patch/latest)](https://github.com/DecimalTurn/toml-patch/actions/workflows/test-and-build.yml)

补丁、解析和字符串化 [TOML](https://toml.io/en/) （v1.1.0），同时保留注释、空格和格式。

这个项目开始于 [原始toml-patch](https://github.com/timhall/toml-patch) 但是已经发展成为一个独立的项目，在可靠性和特性上有了显著的改进。我们增加了对TOML v1.1的支持，引入了新的api，比如 `TomlDocument` 和 `TomlFormat` 类，通过增加测试修复了许多bug [toml-test](https://github.com/toml-lang/toml-test).

我们希望如果有一天原作者回来，这些改进可以被纳入上游，但在那之前，这个项目是积极维护的版本。

## 文档

-   [安装](https://npmcn.com/package/%40decimalturn/toml-patch/#readme-installation)
-   [API](https://npmcn.com/package/%40decimalturn/toml-patch/#readme-api)
-   [Patch-lite](https://npmcn.com/package/%40decimalturn/toml-patch/#readme-patch-lite)
-   [评论所有权](https://npmcn.com/package/%40decimalturn/toml-patch/#readme-comment-ownership)
-   [日期/时间处理和时态](https://npmcn.com/package/%40decimalturn/toml-patch/#readme-datetime-handling--temporal)
-   [格式化](https://npmcn.com/package/%40decimalturn/toml-patch/#readme-formatting)
-   [更新日志](https://github.com/DecimalTurn/toml-patch/blob/v3.3.2/CHANGELOG.md)
-   [贡献](https://github.com/DecimalTurn/toml-patch/blob/v3.3.2/CONTRIBUTING.md)
-   [MIT许可证](https://github.com/DecimalTurn/toml-patch/blob/v3.3.2/LICENSE)

## 安装

tom -patch是无依赖的，可以通过你喜欢的包管理器安装。

_以NPM为例_

```
$ npm install --save @decimalturn/toml-patch
```

对于独立的lite发行版，安装 `lite` npm dist-tag:

```sh
$ npm install --save @decimalturn/toml-patch@lite
```

对于浏览器使用，您可以使用unpkg：

```html
<script type="module">
  import * as TOML from 'https://unpkg.com/@decimalturn/toml-patch@v3.3.2/dist/toml-patch.js';
</script>
```

## API

overwrite(tomlString: string): void TOML -patch为一次性操作提供了功能性API，为需要对同一TOML文档进行多次操作的工作流提供了面向文档的API。

看到 [API参考](https://github.com/DecimalTurn/toml-patch/blob/v3.3.2/docs/API.md) 用于 `patch`， `parse`， `stringify` 和 `TomlDocument` 类。

快速开始，像这样修补现有的TOML字符串：

```js
import { patch } from '@decimalturn/toml-patch';

const existing = 'title = "TOML example"\nowner.name = "Bob"\n';
const updated = patch(existing, {
  title: 'TOML example',
  owner: { name: 'Tim' }
});
```

## Patch-lite

`patch-lite` 是一个较小的、只允许编辑的发行版，适用于只需要更新现有TOML值的应用程序，比如更新包版本。它暴露了相同的 `patch` 带有两个参数的名称 `(existing, updated)` 签名。

它不是主包的一部分：主包只提供完整的API。组件中安装精简版 `lite` NPM分区标签，然后用同样的说明符导入它：

```sh
npm install --save @decimalturn/toml-patch@lite
```

```js
import { patch } from '@decimalturn/toml-patch';

const existing = 'version = "1.0.0"\n';
const updated = patch(existing, { version: '1.0.1' });
// updated === 'version = "1.0.1"\n'
```

dist-tag tarball将它的根导出映射到生活构建，所以没有 `patch-lite` 子路径: `import { patch } from '@decimalturn/toml-patch/patch-lite'` 失败与 `ERR_PACKAGE_PATH_NOT_EXPORTED`． 两者之间的切换是安装更改，而不是代码更改。

lite函数只编辑现有的原始值，并保留编辑值之外的所有源文本，包括注释、空格、行结束符和前导BOM。添加或删除键，数组长度更改，重新排序，重命名，原语/容器类型更改和不支持的值类型在产生任何输出之前抛出。日期/时间值可以自定义给出 `Date` 子类或类 `Temporal` 对象;两者都序列化为现有行的形状。使用完整的 `patch()` 用于添加，删除，移动，重命名和高级格式。

不像 `patch()`， lite分布对其输出不执行编码验证：它不拒绝包含未配对的UTF-16代理的字符串，这些代理不能表示为有效的TOML/UTF-8。使用完整的 `patch()` 当需要此验证时。

这个 [Patch-lite指南](https://github.com/DecimalTurn/toml-patch/blob/v3.3.2/docs/Patch-Lite.md) 列出每个支持和拒绝的操作及其错误代码，与完整的值编码规则不同 `patch()`，以及测量的大小和吞吐量，这样您就可以检查life分发是否涵盖了您的用例。

## 评论所有权

当 `patch()` 删除或重新排序条目，任何描述该条目的注释（同一行结尾） 注释（或者直接在上面的行注释，中间没有空行）也会随之传播 它，而不是被留下来描述任何在那个地方结束的东西。这适用于根 键, `[table]`/`[[array-of-tables]]` 块，以及多行数组和内联中的元素 表。

```js
import * as TOML from '@decimalturn/toml-patch';
import { strict as assert } from 'assert';

const existing = `
x = 1 # a note about x
y = 2
`;

const patched = TOML.patch(existing, { y: 2 });

assert.strictEqual(patched, `
y = 2
`);
```

看到 [评论所有权指南](https://github.com/DecimalTurn/toml-patch/blob/v3.3.2/docs/Comment-Ownership.md) 对于完整的行为，包括空行如何从所有权和当前范围限制中选择注释。

请注意 `patch()` 默认情况下不重新排序条目。 要使它与传入的对象的键顺序匹配，请启用 `updateOrder` 在 [格式化选项](https://github.com/DecimalTurn/toml-patch/blob/v3.3.2/docs/Formatting.md#updateorder).

## 日期/时间处理和时间

将TOML日期/时间值解析为自定义值 `Date` 子类(`LocalDate`， `LocalTime`， `LocalDateTime`， `OffsetDateTime`)。集 `temporal: true` 接收 [时间](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Temporal) 而不是对象。 `stringify()` 和 `patch()` 自动检测时态对象并正确序列化它们。小数秒保持源精度，包括亚毫秒数字。

### 启用时间

这个 `temporal: true` 选择需要 `Temporal` 在运行时可用：

| 运行时 | 如何启用 |
| --- | --- |
| **node . js 26 +** | 内置（无需配置） |
| **node . js至24** | `node --harmony-temporal` 国旗 |
| **node . js 14日至26日** | [@js-temporal / polyfill](https://www.npmjs.com/package/@js-temporal/polyfill) |

```js
import * as TOML from '@decimalturn/toml-patch';

// Node 26+ (native) or Node 20–24 with --harmony-temporal:
const obj = TOML.parse('d = 2024-01-15\n', { temporal: true });
// obj.d → Temporal.PlainDate

// All Node versions with the polyfill:
import { Temporal } from '@js-temporal/polyfill';
globalThis.Temporal = Temporal;
const obj2 = TOML.parse('d = 2024-01-15\n', { temporal: true });
// obj2.d → PlainDate (polyfill)
```

> **注意：** 只有基于偏移量的时区(`+05:30`， `Z`)在TOML中是支持的。IANA时区注释(例如， `[Asia/Kolkata]`)将抛出错误。

看到 [日期/时间指导](https://github.com/DecimalTurn/toml-patch/blob/v3.3.2/docs/Dates.md) 详细信息和示例。

## 格式化

这个 `TomlFormat` 类控制在字符串化和修补操作期间如何格式化TOML文档。

```typescript
class TomlFormat {
  newLine: string
  trailingNewline: number
  trailingComma: boolean
  bracketSpacing: boolean
  inlineTableStart?: number
  truncateZeroTimeInDates: boolean
  useTabsForIndentation?: boolean
  indentWidth: number
  minimumDecimals?: number
  minimumTimeDecimals?: number
  leadingBom: boolean
  updateOrder?: boolean
  multilineTable: boolean | number | 'auto' | 'parent'
  multilineArray: boolean | number | 'auto' | 'parent'

  static default(): TomlFormat
  static autoDetectFormat(tomlString: string): TomlFormat
}
```

从……开始 `TomlFormat.default()` 重写你需要的选项。例如:

```js
import { stringify, TomlFormat } from '@decimalturn/toml-patch';

const format = TomlFormat.default();
format.newLine = '\r\n';
format.trailingNewline = 0;
format.trailingComma = true;
format.bracketSpacing = false;
format.indentWidth = 4;
format.multilineTable = 'parent';

const toml = stringify({
  title: 'My App',
  tags: ['dev', 'config'],
  database: { host: 'localhost', port: 5432 }
}, format);

```

看到 [格式参考](https://github.com/DecimalTurn/toml-patch/blob/v3.3.2/docs/Formatting.md) 对于完整的选项列表，自动检测行为， `updateOrder` 还有更多例子。

## 常见问题

### @decimalturn/toml-patch 是什么？

修补、解析和字符串化TOML，同时保留注释、空白和格式。

### 如何安装 @decimalturn/toml-patch？

在项目目录运行 npm install @decimalturn/toml-patch，或使用 pnpm add / yarn add / bun add。

### @decimalturn/toml-patch 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @decimalturn/toml-patch 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @decimalturn/toml-patch 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=16。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @decimalturn/toml-patch 可以商用吗？

@decimalturn/toml-patch 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @decimalturn/toml-patch 还在维护吗？

最新版本 3\.3\.2 发布于 2026/11/01（2 天前）；至今共发布 58 个版本，其中过去 12 个月发布了 49 个；首次发布于 2025/04/12。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

