小编rea*_*guy的帖子

使用 json 文件动态导入不起作用 typescript

所以我编写了一个这样的函数来获取多个环境的测试数据:

export class DataHelper {
  public static async getTestData(fileName: string): Promise<any> {
    return await import(`../${fileName}`);
  }
}
Run Code Online (Sandbox Code Playgroud)

这将抛出:错误:找不到模块'../test-data.json'

await DataHelper.getTestData('test-data.json')
Run Code Online (Sandbox Code Playgroud)

但这会起作用:

await DataHelper.getTestData('TestScript')
Run Code Online (Sandbox Code Playgroud)

这也将起作用:

await import('../test-data.json')
Run Code Online (Sandbox Code Playgroud)

这是我的 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__/*"]
}
Run Code Online (Sandbox Code Playgroud)

谁能解释发生了什么事以及我应该做什么?

typescript

5
推荐指数
1
解决办法
2万
查看次数

标签 统计

typescript ×1