reactjs - 打字稿找不到声明文件
问题描述
我不知道为什么,但打字稿找不到我的声明文件,即使我有一个。谁能明白这是为什么?
我的项目结构:
scr
- main.ts
- dec.d.ts
str-utils
- index.js
进口:
import {strReverse, strToLower} from '../str-utils/index.js'
我的声明文件(dec.d.ts):
declare module "str-utils"
我的打字稿配置:
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": false,
"outDir": "dist"
},
"include": [
"src/**/*",
"src/dec.d.ts"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
谁能看到我在这里做错了什么?
解决方案
名称的一般规则declare module "{name}"
是它应该与您用于导入模块的名称相同。所以,在这种情况下,declare module '../str-utils/index.js'
。但这不起作用,因为declare module "{name}"
不适用于相对路径。您有两种选择来解决此问题:
1. 使导入非相对:
您修改 tsconfig 以使其str-utils
在没有相对导入的情况下可用。
{
"compilerOptions": {
// other options
"paths": {
"string-utils": ["./str-utils/index.js"]
},
},
// other options
}
str-utils
现在您可以通过导入import {strReverse, strToLower} from 'str-utils'
,因此您的模块声明有效。
2. 将声明文件移动到str-utils
文件夹中
首先,您需要declare module "str-utils"
从声明文件中删除。它应该看起来像这样:
// no wrapping declare module "name" anymore
export function strReverse(arg: string): string;
export function strToLower(arg: string): string;
然后您需要重命名声明文件名以匹配您要扩充的模块的文件名。在这个例子中,我们想要扩充index.js
,所以类型声明的文件名应该是index.d.ts
. 对于这种方法,您的文件夹结构应如下所示:
src
- main.ts
str-utils
- index.d.ts
- index.js
推荐阅读
- import - QGis 中的 DWG/DXF 导入失败
- reactjs - Next.js & Axios - 将 Axios 请求中的 statusCode 500 转发到 Next.js
- html - 在 Iphone 屏幕中将表格单元格转换为表格行
- python - 如何为 VSCode 安装以前版本的 Python 扩展
- .net-core - 获取指定AD组的所有用户只返回一个用户
- apache-spark - 由于 org.apache.spark.SparkException,我无法在 EMR 集群中运行我的 spark 程序
- java - 其他类中的JButton调用函数
- reactjs - 需要解释事件更改处理程序代码
- python - 如何为什么是 for-loops w 累积索引
- html - 使 1 张桌子看起来像 2 张桌子放在一起