javascript - 如何从 npm 声明 javascript 子模块的类型?

标签 javascript node.js reactjs typescript npm

我的项目中有 JS/TS 代码库。一些文件看起来像:

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

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

在 VS Code 和 tsc 结果中我有错误:

Could not find a declaration file for module '@some-lib/things/something'.

'/Users/user/Projects/project/node_modules/@some-lib/things/something/index.jsx' implicitly has an 'any' type.

Try npm install ... if it exists or add a new declaration (.d.ts) file containing 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;
}
但我得到这个错误:

Invalid module name in augmentation.
Module '@some-lib/things/something' resolves to an untyped module at '/Users/user/Projects/project/node_modules/@some-lib/things/something/index.jsx', which cannot be augmented.


请帮我。如何从带有子目录/子模块的 npm 声明 JS 库的 TypeScript 类型?

最佳答案

我找到了解决方案。
如果要创建d.ts对于来自 npm-modules 的 js/jsx 文件,您可以像这样导入:

// this is reference to ./node_modules/@some-lib/things/something/index.js
import Something from '@some-lib/things/something' 
你需要
  • 添加 paths给您的tsconfig.json :
  • {
     "compilerOptios": {
        // ...
        "baseUrl": ".", // just require for "paths"
        "paths": {
          "@some-lib/*": ["src/types/some-lib"] // 'src/types' is just for example
        }
      }
    }
    
  • 创建文件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/ 开始例如。
    我真的希望这会对你有所帮助,祝你好运!

    关于javascript - 如何从 npm 声明 javascript 子模块的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63016869/

    相关文章:

    Javascript onclick 对象相关方法

    javascript - Node.js:mongoose .populate() 未显示数据

    javascript - ReactJS 处理大量状态数据

    javascript - React如何设置父组件的状态

    javascript - 有没有一种简单的方法可以用 javascript/jquery 倒带 html 视频元素?

    javascript - 关于功能及参数

    node.js - 如何在 Electron 生成器中添加发布者

    node.js - 使用 SQLite3 进行单元测试

    javascript - 无法在 Google Pay TEST 环境和订单总额中添加测试卡

    javascript - 在空输入字段 ReactJS 上显示错误