【问题标题】:DefinedTypes file not taken into account when not in the /node_modules/@types/* folder不在 /node_modules/@types/* 文件夹中时不考虑 DefinedTypes 文件
【发布时间】:2019-02-25 16:46:01
【问题描述】:

似乎我的打字稿编译器在模块(./node_modules//index.d.ts)中时没有检测到模块的DefinedTypes文件,而是在@types文件夹(./node_modules/@types)中检测到它们//index.d.ts)。

例如使用 express-validator,该模块带有其定义的类型(请参阅:https://github.com/milkeg/testDefinedType/blob/master/node_modules/express-validator/index.d.ts)但是当我尝试使用 tsc 命令编译时,出现以下错误:

app.ts:5:28 - error TS2307: Cannot find module 'express-validator'.

5 import * as validator from 'express-validator';

我的 tsconfig.json 文件是:

{
    "compilerOptions": {
      "outDir": "./build",
      "allowJs": true,
      "target": "es2018",
      "alwaysStrict": true,
    },
    "include": [
      "./**/*",
    ],
    "exclude": [
      "./node_modules/**/*",
      "./build/**/*"
    ],
}

我尝试将“./node_modules/**/*.d.ts”添加到包含选项,但没有帮助。

示例的回购:https://github.com/milkeg/testDefinedType

我应该进行哪些更改以确保 tsc 考虑到模块本身内的 .d.ts 文件(不仅在 ./node_modules/@types/* 下)?

【问题讨论】:

  • 将“moduleResolution”更改为“node”是否是解决问题的好方法?
  • 似乎将 "module": "commonjs" 添加到 tsconfig.json 解决了这个问题。我不清楚为什么。
  • 如果您在node_modules 下有模块,您肯定希望将moduleResolution 设置为node。设置"module": "commonjs" 将默认moduleResolution 更改为node;见the compiler options page

标签: node.js typescript


【解决方案1】:

只需添加

"typeRoots": [
  "./node_modules/@types",
  "./path/to/custom/dtsfolder/"
],

致您的tsconfig.json

【讨论】:

  • 我试过了,但没有解决问题:tsconfig.json 文件:gist.github.com/milkeg/7cecf1cb4e91fbbe97f8050555835ee7
  • 我认为您不必直接定位到 d.ts 文件,而是包含它的文件夹:"./node_modules/express-validator/"
  • 当我尝试不使用 .d.ts 时,我遇到以下错误:“错误 TS2688:找不到‘build’的类型定义文件。”似乎模块中的所有文件夹都已检查。
猜你喜欢
  • 2020-02-16
  • 1970-01-01
  • 2013-07-08
  • 1970-01-01
  • 2020-05-28
  • 1970-01-01
  • 2013-10-09
  • 2016-03-28
  • 2021-08-27
相关资源
最近更新 更多