【问题标题】:typescript compiling types under node_modules even after excluding themtypescript 在 node_modules 下编译类型,即使在排除它们之后
【发布时间】:2018-04-28 10:23:13
【问题描述】:

在尝试编译我的打字稿源代码时,我看到编译器也在尝试编译我的 node_modules 文件夹下的类型。 我正在使用 typescript 2.6.1,我的 tsconfig 文件如下

 {
  "compilerOptions": {
  "allowSyntheticDefaultImports":true,
  "outDir": "./dist",
  "mapRoot": "./dist",
  "module": "commonjs",
  "target": "es6",
  "sourceMap": true,
  "sourceRoot": "./source",
  "removeComments": false
},
"exclude": [
  "node_modules",
  "test"
],
  "include": [
  "source/*.ts"
]
}

当我运行以下命令“tsc -w -p tsconfig.json”时,出现以下错误

 node_modules/@types/es6-promise/index.d.ts(11,15): error TS2300: Duplicate identifier 'Promise'.

【问题讨论】:

    标签: typescript tsconfig


    【解决方案1】:

    看完这篇文档,我得到了答案 https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

    在@types、typeRoots 和类型部分下

    他们提到了

    指定 "types": [] 以禁用自动包含 @types 包。

    更新后的tsconfig.json如下

    {
      "compilerOptions": {
       "allowSyntheticDefaultImports":true,
       "outDir": "./dist",
       "mapRoot": "./dist",
       "module": "commonjs",
       "target": "es6",
       "sourceMap": true,
       "sourceRoot": "./source",
       "removeComments": false,
       "types": []
     },
     "exclude": [
       "node_modules",
       "test"
     ],
     "include": [
       "source/*.ts"
     ]
    }
    

    【讨论】:

      【解决方案2】:

      为什么?

      当 TypeScript 版本不对应时也会发生这种情况。

      例如您在全局 npm 缓存中运行 2.9.x,并且在项目 node_modules 中本地安装了 TypeScript 3.5.x。


      测试

      您可以通过运行“npx tsc”对此进行测试,但这仅在您将 TypeScript 保存为依赖项、运行“npm install”并且您拥有 npm 5.2.x 或更高版本时才有效。

      否则,您可以使用“npm list typescript”检查本地 TypeScript 版本,使用“npm list typscript -g”检查全局 TypeScript 版本


      解决方案

      如果在“npx tsc”方法的情况下,它通过了,或者在版本不匹配的第二种情况下,您只需要确保您的本地 TypeScript 版本与您的全局 TypeScript 版本一致,或者反之亦然。


      其他说明:

      “npx”将使用项目本地“node_modules”文件夹中的 Node 包运行命令。

      如果您不知道,请查看 Node Version Manager,它非常适合在 Node 版本之间动态切换。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-04
        • 2021-04-15
        • 2017-01-02
        • 1970-01-01
        • 2016-09-19
        • 1970-01-01
        • 2019-02-13
        相关资源
        最近更新 更多