如何在`tsconfig.json`中正确使用自定义声明文件?

时间:2019-12-24 10:20:52

标签: javascript typescript tsconfig

以下是演示目录:

- rootDir
    - node_modules
    - src
        - index.ts
    - types
        - global.d.ts
    - package.json
    - README.md
    - tsconfig.json
// index.ts
const _var = global_var; // `global_var` exist in runtime certainly and it is from template or other script.
// global.d.ts
declare const global_var: any;
// tsconfig.json
{
  "compilerOptions": {
    "target": "ESNext",
    "sourceMap": true,
    "module": "esnext",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "noUnusedLocals": true,
    "baseUrl": ".",
    "typeRoots": [
      "./types"
    ],
    "types": [
      "global"
    ]
  },
  "include": [
    "./src/**/*.ts"
  ],
  "compileOnSave": false
}

现在我在global_var文件index.ts中的Cannot find name 'global_var'.ts(2304)上遇到类型错误。很显然,tsconfig.json文件出了点​​问题……但是这有什么问题呢?

然后,我尝试修复typeRootstypes的值,并通过以下操作得到确定:

// tsconfig.json
{
  "compilerOptions": {
    ...
    "typeRoots": [],
    "types": [
      "./types/global"
    ]
  },
  "include": [
    "./src/**/*.ts"
  ],
  "compileOnSave": false
}

这与上面有什么区别? typescript找不到第一个tsconfig.json文件跟随/types/global路径的声明文件吗?如果没有,那是什么?

0 个答案:

没有答案