首页 > 解决方案 > 打字稿找不到声明文件

问题描述

我不知道为什么,但打字稿找不到我的声明文件,即使我有一个。谁能明白这是为什么?

我的项目结构:

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"
  ]
}

谁能看到我在这里做错了什么?

标签: reactjstypescripttypes

解决方案


名称的一般规则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

推荐阅读