TypeScript 之tsconfig.json

最近,在一个项目中引入TypeScript时,出现下面的报错

node_modules/@types/requirejs/index.d.ts:38:2 - error TS2309: An export assignment cannot be used in a module with other exported elements.

38  export = mod;
    ~~~~~~~~~~~~~

node_modules/@types/requirejs/index.d.ts:422:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'require' must be of type 'Require', but here has type 'Require'.

422 declare var require: Require;
                ~~~~~~~

  node_modules/@types/node/globals.d.ts:167:13
    167 declare var require: NodeJS.Require;
                    ~~~~~~~
    'require' was also declared here.

报错原因为第三方库requirejs与node的声明文件冲突。

此时,我就开始思考为什么我在tsconfig.json中配置了

"exclude": [ "node_modules"]

为什么tsc 还是执行到 node_modules/@types 中去了?

后来,仔细翻看官网文档才发现

默认所有可见的"@types"包会在编译过程中被包含进来。 node_modules/@types文件夹下以及它们子文件夹下的所有包都是可见的; 也就是说, ./node_modules/@types/,../node_modules/@types/和../../node_modules/@types/等等。

此时,如果指定了typeRoots,只有typeRoots下面的包才会被包含进来。 比如:

{
   "compilerOptions": {
       "typeRoots" : ["./typings"]
   }
}

这个配置文件会包含所有./typings下面的包,而不包含./node_modules/@types里面的包。

如果指定了types,只有被列出来的包才会被包含进来。 比如:

{
   "compilerOptions": {
        "types" : ["node", "lodash", "express"]
   }
}

这个tsconfig.json文件将仅会包含 ./node_modules/@types/node,./node_modules/@types/lodash和./node_modules/@types/express。/@types/。 node_modules/@types/*里面的其它包不会被引入进来。通过指定"types": []来禁用自动引入@types包。

这样设置之后,就很好的解决了我项目中的问题

你可能感兴趣的:(TypeScript 之tsconfig.json)