導入 JSON
在 Github 上編輯
JSON 檔案可以使用 import
關鍵字在 JS 和 TS 檔案中導入。這使得在函式庫中包含靜態資料更加容易。
JSON 檔案可以在 JS 和 TS 模組中導入。 這樣做時,您需要指定 "json" 導入斷言類型。
./main.ts
import file from "./version.json" with { type: "json" };
console.log(file.version);
也支援動態導入。
./main.ts
const module = await import("./version.json", {
with: { type: "json" },
});
console.log(module.default.version);
./version.json
{
"version": "1.0.0"
}
使用 Deno CLI 在本地端執行此範例
deno run https://deno-docs.dev.org.tw/examples/scripts/importing_json.ts/main