如何阻止 typescript 2.0 在解析模块时遍历所有父目录?

How to block typescript 2.0 from walking up all parent directories while resolving modules?

已升级到 Typescript 2.0 (2.1.6),它开始出现 "Duplicate identifier" 错误。仔细查看后发现 Typescript 开始从所有上层目录(基本上是其他项目)导入 @types。

要让 Typescript 忽略上层 node_modules 应该如何配置?

src
 └── node_modules << *** how to ignore it? ***
     └── @types

 └── my.app << *** how to build this folder and down only? ***
         └── node_modules
             └── @types

编辑:这是我遇到的错误示例:

typings/globals/mocha/index.d.ts(30,13):错误 TS2300:重复标识符 'describe'。 ../../../node_modules/@types/jasmine/index.d.ts(9,18):错误 TS2300:重复标识符 'describe'.

listFiles: true 显示@types/jasmine 正在从上层文件夹导入:

C:/src/<project>/<folder>/<my.app>/typings/globals/mocha/index.d.ts
C:/src/node_modules/@types/jasmine/index.d.ts

如果我重命名上层 node_modules 文件夹,则构建成功。

您可以在编译器选项中指定根目录。 See the official documentation.

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

official documentation指定当前目录下的node_modules,除非指定typeRoots.

,否则将遍历所有父目录

所以理论上,答案应该是这样的:

{
  "compilerOptions": {
    "typeRoots": [
      "./node_modules/@types"
    ]
  }
}

因为您仍想包含当前目录中的类型。

不幸的是这对我来说似乎无法正常工作。

我遇到了这个问题,并从文档中推断出与@peterjwest 相同的事情 - 但是在阅读了这个问题后:https://github.com/Microsoft/TypeScript/issues/27026,我想我误解了 typeRoots 的意图(这似乎仅在配置全局类型而不是模块类型时有用。

在我的例子中,解决方案是为冲突类型配置 baseUrlpaths(在我的例子中是 React):

tsconfig.json:

{
    "compilerOptions": {
        ...
        "baseUrl": ".",
        "paths": {
            "react": ["node_modules/@types/react"]
        }
    }
    ...
}

这似乎适用于告诉打字稿我想从本地 node_modules.

专门解析该类型

这对任何人都有帮助,在我的 tsconfig.json 中设置 "types": [] 对我有用。请参阅此 github 评论。

https://github.com/Microsoft/TypeScript/issues/13992#issuecomment-279020210