所以我写了一个这样的函数来获取多个环境的测试数据:
export class DataHelper {
public static async getTestData(fileName: string): Promise<any> {
return await import(`../${fileName}`);
}
}
这将抛出:错误:找不到模块'../test-data.json'
await DataHelper.getTestData('test-data.json')
但这会起作用:
await DataHelper.getTestData('TestScript')
这也行得通:
await import('../test-data.json')
这是我的 tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"sourceMap": true,
"outDir": "./lib",
"moduleResolution": "node",
"baseUrl": ".",
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"resolveJsonModule": true
},
"include": ["src", "example/**/*"],
"exclude": ["node_modules", "**/__tests__/*"]
}
谁能解释发生了什么以及我应该怎么做?
最佳答案
如果不使用导入断言,您实际上无法在 TypeScript 中动态导入 json 文件。 TypeScript 仅允许您通过配置属性导入具有 json
扩展名的文件,遗憾的是,这与 JavaScript 规范不同,后者可能会让很多人感到困惑。以下是导入断言的样子,但 Node.js 目前不支持它们:
// static import
import data from "./foo.json" assert { type: "json" };
// dynamic import
await import("./foo.json", { assert: { type: "json" } });
TLDR 是你必须断言的,因为出于安全原因,文件扩展名不能用于确定文件类型。
无论如何,在 Node.js 中异步获取 JSON 的最佳方法是通过 fs
读取文本,然后使用 JSON.parse
。至少,在 Node.js 添加对导入断言的支持之前,我认为这几年不会稳定下来。
这是一个例子:
import { readFile } from "fs/promises";
async function readJsonFile(path) {
const file = await readFile(path, "utf8");
return JSON.parse(file);
}
readJsonFile("./package.json").then((data) => {
console.log(data);
});
之后
您仍然可以使用require
来加载 JSON 文件,但我强烈建议不要这样做,因为它是同步的,所以它会停止您的程序的整个过程。
关于typescript - 使用 json 文件动态导入不起作用 typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70601733/