创建 React App 找不到声明的模块

Ami*_*avi 7 typescript tsconfig typescript-typings create-react-app react-tsx

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

在项目的根目录中存在tsconfig.json一个名为types. 在类型文件夹中,我modulename.d.ts为在 node_modules 没有默认类型的模块创建了一个文件,并且在@types\module-name.

但我在编译时收到错误。

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

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

// .d.ts
declare module 'foo-react' {
    import * as React from 'react';
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这是 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"]
}
Run Code Online (Sandbox Code Playgroud)

Ami*_*avi 4

结果发现

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

Typescript 手册中类型编译器选项的定义

\n
\n

--types string[] 要包含的类型定义的名称列表。有关更多详细信息,请参阅@types、\xe2\x80\x94typeRoots 和\xe2\x80\x94types 。

\n
\n