#独家
如何正确声明一个 react + ts 组件包?

2023-08-05 0 2,742

组件

const MyComponent = () => {
  return <div>hi</div>;
};
export default MyComponent;

package.json

{
  "name": "my-library",
  "type": "module",
  "module": "./dist/main.es.js",
  "types": "./types/index.d.ts",
  "typings": "./types/index.d.ts",
  "exports": {
  ".": {
    "import": "./dist/main.es.js"
  }
},

index.d.ts

declare module "my-library";

使用

import DDD from "my-library";

export default function Demo() {
  return (
    <>
      <DDD />
    </>
  );
}

目前在使用的时候报错

Could not find a declaration file for module 'my-library'. '/my-library/dist/main.es.js' implicitly has an 'any' type.
  There are types at '/demo/node_modules/my-library/types/index.d.ts', but this result could not be resolved when respecting package.json "exports". The 'my-library' library may need to update its package.json or typings.

1 import DDD from "my-library";

如何在 index.d.ts 文件中正确声明这个组件

declare module "my-library" {
  import { FunctionComponent } from 'react';

  const MyComponent: FunctionComponent;

  export default MyComponent;
}

FunctionComponent 是 React 提供的类型,它表示一个函数组件。在这个声明文件中,我们声明 “my-library” 模块有一个默认导出,它是一个函数组件。

然后在你的 package.json 文件中,确保 “types” 和 “typings” 字段指向这个声明文件:

{
  "name": "my-library",
  "type": "module",
  "module": "./dist/main.es.js",
  "types": "./index.d.ts",
  "typings": "./index.d.ts",
  "exports": {
    ".": {
      "import": "./dist/main.es.js"
    }
  }
}

这样,当其他 TypeScript 项目使用 “my-library” 模块时,TypeScript 就会找到这个声明文件,知道这个模块提供了一个默认导出,它是一个函数组件,然后就能进行类型检查了。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

1. JK下载官网所有资源来源于开发团队,加入会员即可下载使用!如有问题请联系右下角在线客服!
2. JK下载官方保障所有软件都通过人工亲测,为每位会员用户提供安全可靠的应用软件、游戏资源下载及程序开发服务。
3. JK开发团队针对会员诉求,历经多年拥有现今开发成果, 每款应用程序上线前都经过人工测试无误后提供安装使用,只为会员提供安全原创的应用。
4. PC/移动端应用下载后如遇安装使用问题请联系右下角在线客服或提交工单,一对一指导解决疑难。

JK软件下载官网 技术分享 如何正确声明一个 react + ts 组件包? https://www.jkxiazai.com/2397.html

JK软件应用商店是经过官方安全认证,保障正版软件平台

相关资源

官方客服团队

为您解决烦忧 - 24小时在线 专业服务