如何在npm的JavaScript子模块中声明类型?

4

我在项目中有JS/TS代码库,其中一些文件看起来像这样:

import Something from '@some-lib/things/something'; // index.jsx file here

const someFunction = () => {
  // do something with "Something"
};


在 VS Code 和 tsc 中,我遇到了以下错误:
``` 找不到模块 '@some-lib/things/something' 的声明文件。 '/Users/user/Projects/project/node_modules/@some-lib/things/something/index.jsx' 隐式地具有 'any' 类型。 如果存在,请尝试运行命令 npm install ...,或者创建一个新的声明文件(.d.ts),其中包含 declare module '@some-lib/things/something'; ```
我尝试通过创建文件 `src/@types/@some-lib/index.d.ts` 并添加以下内容来增加定义:
declare module '@some-lib/things/something' {
  const Something: (props: React.SVGProps<SVGSVGElement> & {
    size?: number,
    color?: string,
    inline?: boolean,
    className?: string,
  }) => React.ReactElement;

  export default Icon;
}

但我遇到了这个错误:

增强时模块名无效。
模块“@some-lib/things/something”在“/Users/user/Projects/project/node_modules/@some-lib/things/something/index.jsx”处解析为未类型化的模块,无法进行增强。

请帮我。我该如何为npm中具有子目录/子模块的JS库声明TypeScript类型?

2个回答

1
I found solution.
如果你想从像这样导入的npm模块的js/jsx文件中创建d.ts文件: d.ts文件的创建方法如下:
// this is reference to ./node_modules/@some-lib/things/something/index.js
import Something from '@some-lib/things/something' 

你需要:
  1. 在你的 tsconfig.json 中添加 paths
{
 "compilerOptios": {
    // ...
    "baseUrl": ".", // just require for "paths"
    "paths": {
      "@some-lib/*": ["src/types/some-lib"] // 'src/types' is just for example
    }
  }
}
  1. 创建文件 src/types/@some-lib/things/something.d.ts,并添加以下内容:
declare module '@some-lib/things/something' { // equal to import
  const Something = number; // number just for example

  export = Something;
}

据我所知,您的 d.ts 文件路径应该与来自 node_modules 的路径相同,只是其根目录在示例中从 src/types/ 开始。
我真心希望这能帮到您,祝您好运!

-1

抱歉之前的评论看起来不太好... 我需要在tsconfig中添加什么才能使它工作?我已经将导入添加到声明中,现在我有两个相同的错误:找不到模块的声明文件... - krutoo
我的tsconfig.json文件如下:{ "compilerOptions": { "module": "commonjs", "esModuleInterop": true, "target": "es2017", "lib": ["es2017", "esnext.asynciterable"], "noImplicitAny": true, "moduleResolution": "node", "sourceMap": true, "outDir": "lib", "emitDecoratorMetadata": true, "experimentalDecorators": true, "skipLibCheck": true, "strict": true }, "include": [ "src" ] } - Mihályi Zoltán
这个配置中没有“paths/typeRoots”选项。我的意思是,我该如何告诉TSC,我的npm子模块应该被自定义的d.ts文件中的信息所替换? - krutoo
"compilerOptions": { "typeRoots": ["node_modules/@types", "src/@types"] } - Mihályi Zoltán

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接