创建 React App 找不到声明的模块
Posted
技术标签:
【中文标题】创建 React App 找不到声明的模块【英文标题】:Create React App cannot find declared module 【发布时间】:2019-08-09 08:31:03 【问题描述】:我有一个使用 CRA 打字稿创建的项目。
在项目的根目录下存在tsconfig.json
和一个名为types
的文件夹。在 types 文件夹中,我为在 node_modules 没有默认类型的模块创建了一个 modulename.d.ts
文件,并且在 @types\module-name
也没有任何内容。
但我在编译时收到错误。
类型错误:找不到模块“名称”的声明文件。 '/*/node_modules/thename/dist/entry.js' 隐含了一个 'any' 类型。
为什么编译器在 types 文件夹中找不到类型声明?
// .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
@types
文件夹的路径(我在项目根目录中自定义的文件夹)应该添加到types
属性而不是paths
属性。 "types":["./@types"]
在@types
文件夹中,其结构类似于@types/<module_name>/index.d.ts
或@types/moduleName.d.ts
。现在该文件可以将该模块声明为any
或详细声明所有类型。
Typescript handbook 中类型编译器选项的定义
--types string[] 要包含的类型定义的名称列表。详情请见@types, —typeRoots and —types。
【讨论】:
以上是关于创建 React App 找不到声明的模块的主要内容,如果未能解决你的问题,请参考以下文章
无法加载在 'package.json » eslint-config-react-app' 中声明的插件 'flowtype':找不到模块 'eslint/use-at-your-own-risk'
错误:“找不到模块 'react-search-input' 的声明文件”