[英]Typescript cant find declaration file
Im not sure why but typescript cannot find my declaration file even though I have one.我不知道为什么,但 typescript 找不到我的声明文件,即使我有一个。 Can anyone see why this is?
谁能明白这是为什么?
My project structure:我的项目结构:
scr
- main.ts
- dec.d.ts
str-utils
- index.js
The import:进口:
import {strReverse, strToLower} from '../str-utils/index.js'
My declaration file (dec.d.ts):我的声明文件(dec.d.ts):
declare module "str-utils"
My typescript config:我的 typescript 配置:
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": false,
"outDir": "dist"
},
"include": [
"src/**/*",
"src/dec.d.ts"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
Can anyone see what I am doing wrong here?谁能看到我在这里做错了什么?
The general rule for the name of declare module "{name}"
is that it should be the same name you would use to import the module. declare module "{name}"
的名称的一般规则是它应该与您用于导入模块的名称相同。 So, in this case, declare module '../str-utils/index.js'
.因此,在这种情况下,
declare module '../str-utils/index.js'
。 But this will not work because declare module "{name}"
doesn't work for relative paths.但这不起作用,因为
declare module "{name}"
不适用于相对路径。 You have two options to solve this issue:您有两种选择来解决此问题:
1. Making the import non-relative: 1. 使导入非相对:
You modify the tsconfig to make str-utils
available without a relative import.您修改 tsconfig 以使
str-utils
在没有相对导入的情况下可用。
{
"compilerOptions": {
// other options
"paths": {
"string-utils": ["./str-utils/index.js"]
},
},
// other options
}
Now you can import str-utils
via import {strReverse, strToLower} from 'str-utils'
and thus, your module declaration works.现在您可以通过
import {strReverse, strToLower} from 'str-utils'
str-utils
因此您的模块声明有效。
2. Moving the declaration file into the str-utils
folder 2. 将声明文件移动到
str-utils
文件夹中
First, you need to remove declare module "str-utils"
from your declaration file.首先,您需要从声明文件中删除
declare module "str-utils"
。 It should look something like this:它应该看起来像这样:
// no wrapping declare module "name" anymore
export function strReverse(arg: string): string;
export function strToLower(arg: string): string;
Then you need to rename the declaration file name to match the file name of the module you want to augment.然后您需要重命名声明文件名以匹配您要扩充的模块的文件名。 In this example, we want to augment
index.js
, so the type declaration's file name should be index.d.ts
.在这个例子中,我们想要扩充
index.js
,所以类型声明的文件名应该是index.d.ts
。 Your folder structure should look like that for this approach:对于这种方法,您的文件夹结构应如下所示:
src
- main.ts
str-utils
- index.d.ts
- index.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.