创建React应用程序找不到声明的模块



我有一个用CRA打字稿创建的项目。

在项目的根部存在tsconfig.json和一个称为types的文件夹。在类型文件夹我创建了一个在Node_modules上没有默认打字的模块的modulename.d.ts文件,并且在@typesmodule-name上也没有任何内容。

,但我在编译时会出现错误。

类型错误:找不到模块" thename"的声明文件。'/*/node_modules/thename/dist/entry.js'隐式具有'任何''类型。

为什么编译器在类型文件夹中找不到类型声明?

// .d.ts
declare module 'foo-react' {
    import * as React from 'react';
    // ...
}

这是tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": { "*": ["types/*"] },
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "plugins": [{ "name": "typescript-tslint-plugin" }],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve"
  },
  "include": ["src"]
}

,所以事实证明

  1. 我将自定义类型文件夹重命名为@types
  2. 应将@types文件夹的路径(我在项目的根部定制一个)添加到types属性中,而不是paths属性。"types":["./@types"]
  3. @types文件夹中,具有@types/<module_name>/index.d.ts@types/moduleName.d.ts之类的结构。现在,该文件可以将该模块声明为any或详细声明所有类型。

类型编译器选项的定义在打字稿手册中

- 类型字符串[]要包含的类型定义名称的名称列表。有关更多详细信息,请参见@Types, - Typeroot和 - 类型。

最新更新