导入 config.json 文件时打字稿总是出错

Typescript always errors when importing a config.json file

我正在使用最新版本的 Visual Studio 代码。 VS Code 使用的是 Typescript v3.3.3。 我已经通过 npm 在本地(save-dev)和全局安装了以下软件包:

  1. TestCafe v1.1.0
  2. Core-JS v3.0.
  3. TypeScript v3.4.1

我还创建了一个 tsconfig.json 文件并添加了 属性 - "resolveJsonModule: true"

我已经创建了一个 config.json 文件,在添加上面的 resolveJsonModule 属性 之后,我的 .ts 文件中正确地提取了它 -

Import config from './config.json';

然而,每当我 运行 我的脚本时,我都会收到以下错误:

    Error: TypeScript compilation failed.
    /Users/test/Documents/Dev_Node/TestCafe/UK/homepage-fixture.ts (2, 20): 
    Cannot find module './config.json'. Consider using '--resolveJsonModule' 
    to import module with '.json' extension at Function._reportErrors (/Users/test/Documents/Dev_Node/TestCafe/node_modules/testcafe/src/compiler/te st-file/formats/typescript/compiler.js:45:15) at TypeScriptTestFileCompiler._reportErrors [as _precompileCode (/Users/test/Documents/Dev_Node/TestCafe/node_modules/testcafe/src/compiler/test-file/formats/typescript/compiler.js:79:40) at TypeScriptTestFileCompiler._precompileCode [as_compileCodeForTestFiles (/Users/test/Documents/Dev_Node/TestCafe/node_modules/testcafe/src/compiler/te 
st-file/api-based.js:110:29) at TypeScriptTestFileCompiler._compileCodeForTestFiles [as precompile (/Users/test/Documents/Dev_Node/TestCafe/node_modules/testcafe/src/compiler/test-file/api-based.js:169:21) at precompile (/Users/test/Documents/Dev_Node/TestCafe/node_modules/testcafe/src/compiler/index.js:70:48) at Compiler._precompileFiles (/Users/test/Documents/Dev_Node/TestCafe/node_modules/testcafe/src/compiler/index.js:66:54) at _precompileFiles (/Users/test/Documents/Dev_Node/TestCafe/node_modules/testcafe/src/compiler/index.js:105:91) at map (/Users/test/Documents/Dev_Node/TestCafe/node_modules/testcafe/src/compiler/i ndex.js:105:41)

我已经尝试过此处提供的解决方案:

但是 none 对我有用。

根据这个长期存在的问题:https://github.com/DevExpress/testcafe/issues/1845 TestCafe 使用自己的 TypeScript 配置,并且不接受您使用的任何 tsconfig.json。

所以在我看来你的选择是:

  • 使用包含 resolveJsonModule 标志的 tsconfig.json 自己编译 TypeScript 代码,只让 TestCafe 看到生成的 JavaScript 代码。 TypeScript 的 outDir 标志在这里可能有助于将文件复制到正确的位置。
  • 创建一个接口(可能命名为 MyConfig)来描述你的配置内容,并导入 JSON 文件 let json: MyConfig = require('./config.json'); 还不如让 TypeScript 自己解决问题,但它应该可以解决 TestCafe 的限制。