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>)。
例外: 無法讀取檔案時,擲回封裝底層檔案系統錯誤的例外。