我有一个用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"]
}
,所以事实证明
- 我将自定义类型文件夹重命名为
@types
- 应将
@types
文件夹的路径(我在项目的根部定制一个)添加到types
属性中,而不是paths
属性。"types":["./@types"]
- 在
@types
文件夹中,具有@types/<module_name>/index.d.ts
或@types/moduleName.d.ts
之类的结构。现在,该文件可以将该模块声明为any
或详细声明所有类型。
类型编译器选项的定义在打字稿手册中
- 类型字符串[]要包含的类型定义名称的名称列表。有关更多详细信息,请参见@Types, - Typeroot和 - 类型。