在使用VSCode时使用typescript中的import语句导入json文件时,我有一些奇怪的行为 . 请注意,这不是打字稿本身只是VSCode突出显示的问题 .

我编辑了我的tsconfig.json,在我的编译器选项中添加了值为true的resolveJsonModule和esModuleInterop,以便在typescript中导入json .

此外,我已将此包添加到我的项目https://www.npmjs.com/package/json-d-ts,并将一个typeRoots属性添加到tsconfig.json,其值为["node_modules/json-d-ts"]

我在一个模块(在src / firebaseApp.ts中找到)中导入了json文件(在src / config / firebaseServiceKey.json中找到),该模块位于父目录中,因此导入如下所示:

import databaseUrl from "./config/firebaseDatabaseURL.json";

VSCode不会抱怨此导入:

Good import highlighting

但是我有另一个模块在项目目录中的不同级别导入相同的文件,该模块位于test / utils.ts,其导入如下所示:

import serviceKey from "../src/config/firebaseServiceKey.json";

这次VSCode似乎不喜欢相对导入并突出显示模块缺失:

enter image description here

任何想法如何修复配置VSCode来解决这个问题?

以下是运行tsc --traceResolution结果的相关部分:

======== Resolving module '../src/config/firebaseServiceKey.json' from '/home/jty/April2018/vs-server/test/utils.ts'. ========
Explicitly specified module resolution kind: 'NodeJs'.
Loading module as file / folder, candidate module location '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json', target file type 'TypeScript'.
File '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json.ts' does not exist.
File '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json.tsx' does not exist.
File '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json.d.ts' does not exist.
Directory '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json' does not exist, skipping all lookups in it.
Loading module as file / folder, candidate module location '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json', target file type 'JavaScript'.
File '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json.js' does not exist.
File '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json.jsx' does not exist.
Directory '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json' does not exist, skipping all lookups in it.
Loading module as file / folder, candidate module location '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json', target file type 'Json'.
File '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json' exist - use it as a name resolution result.
======== Module name '../src/config/firebaseServiceKey.json' was successfully resolved to '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json'. ========

这是我的tsconfig.json

{
"compilerOptions": {
    "module": "commonjs",
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "target": "es6",
    "noImplicitAny": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist",
    "baseUrl": ".",
    "paths": {
        "*": [
            "node_modules/*",
            "src/types/*"
        ]
    }
},
"include": [
    "src/**/*"
],
"typeRoots": [
    "node_modules/json-d-ts"
  ]
}