如何排除`node_modules / @ types / ** / node_modules`?

时间:2018-05-25 13:43:00

标签: angularjs typescript webpack typescript-typings tsconfig

我遇到node_modules/@types中的类型定义正在安装自己的@types依赖项的情况,这些“嵌套”@types与我的顶级@types冲突。

@types
|-angular //v1.5
|-angular-ui-bootstrap
  |-node_modules
    |-@types
       |-angular //v1.6

如何在tsconfig中排除node_modules/@types/**/node_modules

一个警告 - 我正在使用awesome-typescript-loader,may have some limitations

我尝试了什么:

1 - exclude属性中的文件glob,以排除嵌套的node_modules

    compilerOptions.exclude: '../node_modules/@types/**/node_modules'

2 - 明确声明types

    compilerOptions.types: ['angular', 'angular-ui-bootstrap']

3 - typeRoots中的文件glob以排除嵌套的node_modules

    compilerOptions.typeRoots: ['../node_modules/@types/**/!(node_modules)']

我学到了什么

1 - 排除似乎不适用于@types

2 - 包括具有“类型”的类型意味着包括其依赖的@types

3 - typeRoots似乎不适用于文件globs(或者我写的是错误的)

相关:

Exclude @types typings in installed dependencies

https://github.com/Microsoft/TypeScript/issues/9731

https://github.com/Microsoft/TypeScript/issues/11917

https://github.com/s-panferov/awesome-typescript-loader/issues/492

tsconfig - How to ignore @types/whatever/node_modules for a specific directory?

有关我的环境的详细信息

“node”:“8.6.0”, “打字稿:”2.8.3“, “awesome-typescript-loader”:“5.0.0”, “webpack”:“4.8.3”,

3 个答案:

答案 0 :(得分:1)

为此,我发现一个解决方案是在node_modules/@types tsconfig.json设置中指定paths目录。

这是我在tsconfig.json中更改的代码段,您应该可以对其进行调整以适应您的用例。我需要修改baseUrlpaths设置。

   ...
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"],
      "*": ["./node_modules/@types/*"]
    }
   ...

就我而言,我在TS项目中使用绝对URL,因此我的本地文件都相对于@/。我认为,如果您不使用这样的绝对网址,则应在配置中输入以下内容:

   ...
    "baseUrl": ".",
    "paths": {
      "*": ["./src/*", "./node_modules/@types/*"]
    }
   ...

这是我完整的tsconfig.json,其中可能包含很多不相关的信息,仅供参考。

{
  "compilerOptions": {
    "outDir": "./build/",
    "sourceMap": true,
    "allowJs": true,
    "checkJs": true,
    "jsx": "react",
    "target": "es2017",
    "module": "commonjs",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "removeComments": false,
    "preserveConstEnums": true,
    "skipLibCheck": true,
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"],
      "*": ["./node_modules/@types/*"]
    }
  },
  "include": ["**/*", "*"],
  "exclude": ["build", "node_modules", "coverage"]
}

答案 1 :(得分:0)

使用peerDependencies来确保您只有一个版本的依赖项。

即如果我要对角度和角度模拟使用打字,角度模拟将有自己的@ types / angular

@types/angular  // => 1.5.8
@types/angular-mocks // => 1.5.8
@types/angular-mocks/node_modules/@types/angular // => *

要防止安装两个版本的@types/angular,请在package.json文件中将@types/angular声明为peerDependency。

答案 2 :(得分:0)

在 package.json 中使用以下 postinstall 脚本:

for d in node_modules/@types/*/ ; do
  rm -rf ${d}node_modules
done

这将遍历 @types 并删除不需要的传递类型依赖项。

相关问题