API 参考
@powerduck/conf-patch 完整参考,涵盖各导出符号的签名和默认值。
提供两个入口:
@powerduck/conf-patch— 下列所有功能:核心层、文件层、OpenAPI 校验和工具函数。@powerduck/conf-patch/core— 仅包含兼容浏览器的子集:patchContent、setContentValue、deleteContentValue、PatchContentOptions、断言辅助函数,以及ConfigFormat、JsonPatchOp、JsonPathSegment类型。
核心层(兼容浏览器)
patchContent
对配置字符串应用一组 RFC 6902 补丁操作。此函数为纯函数,不访问文件系统。
function patchContent(
content: string,
ops: JsonPatchOp[],
format: ConfigFormat,
options?: PatchContentOptions,
): string;
| 参数 | 类型 | 说明 |
|---|---|---|
content | string | 原始配置内容,必须符合指定的 format。 |
ops | JsonPatchOp[] | 按顺序执行的操作。空数组会原样返回 content。 |
format | ConfigFormat | "json" | "jsonc" | "yaml"。 |
options.strict | boolean | 为 true(默认值)时,操作失败会抛出异常;为 false 时,跳过失败操作并调用 console.warn。 |
返回: 应用补丁后的配置内容(string)。
异常: content 不是字符串或 ops 无效时抛出 TypeError;strict 为 true 时,抛出说明失败操作的错误。
import { patchContent } from "@powerduck/conf-patch/core";
patchContent(
'{"name": "app"}',
[{ op: "add", path: ["version"], value: "1.0.0" }],
"json",
);
// => '{\n "name": "app",\n "version": "1.0.0"\n}'
setContentValue
设置或创建单个值。内部调用 patchContent 执行一次 add 操作。按 RFC 6902 语义,add 替换已有对象属 性,或在数组索引处插入元素。
function setContentValue(
content: string,
path: readonly (string | number)[],
value: unknown,
format: ConfigFormat,
): string;
| 参数 | 类型 | 说明 |
|---|---|---|
content | string | 原始配置内容。 |
path | readonly (string | number)[] | 分段路径,如 ["server", "port"],不能为空。 |
value | unknown | 要写入的值。 |
format | ConfigFormat | 配置格式。 |
返回: 更新后的内容(string)。
setContentValue("server:\n port: 3000\n", ["server", "port"], 8080, "yaml");
deleteContentValue
删除键或数组元素。内部调用 patchContent 执行一次 remove 操作,目标路径必须存在。
function deleteContentValue(
content: string,
path: readonly (string | number)[],
format: ConfigFormat,
): string;
deleteContentValue(
'{"name": "app", "legacy": true}',
["legacy"],
"json",
);
PatchContentOptions
interface PatchContentOptions {
/** When true, failed operations throw. When false, they are skipped with a warning. Default: true */
strict?: boolean;
}
文件层(仅 Node.js / Electron)
readConfigFile
从本地文件路径或 file:// URL 读取 UTF-8 文本。
function readConfigFile(filePath: string): Promise<string>;
| 参数 | 类型 | 说明 |
|---|---|---|
filePath | string | 绝对路径、相对路径或 file:// URL,不能为空。 |
返回: 原始 UTF-8 内容(Promise<string>)。
异常: 无法读取文件时,抛出封装底层文件系统错误的异常。