我有一个使用 CRA typescript 创建的项目。
在项目的根目录下存在 tsconfig.json
和一个名为 types
的文件夹。在 types 文件夹中,我为一个模块创建了一个 modulename.d.ts
文件,该文件在 node_modules 中没有默认类型,而且在 @types\module-name< 中也没有任何内容
.
但是我在编译时得到了错误。
Type error: Could not find a declaration file for module 'thename'. '/*/node_modules/thename/dist/entry.js' implicitly has an 'any' type.
为什么编译器在类型文件夹中找不到类型声明?
// .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"]
}
最佳答案
原来是这样
- 我将自定义类型文件夹重命名为
@types
@types
的路径文件夹(我在项目根目录下自定义的文件夹)应添加到types
属性而不是paths
属性。"types":["./@types"]
- 在
@types
结构类似于@types/<module_name>/index.d.ts
的文件夹或@types/moduleName.d.ts
.现在文件可以将该模块声明为any
或详细声明所有类型。
类型编译器选项的定义 Typescript handbook
--types string[] List of names of type definitions to include. See @types, —typeRoots and —types for more details.
关于typescript - 创建 React App 找不到声明的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55230403/