组件
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 就会找到这个声明文件,知道这个模块提供了一个默认导出,它是一个函数组件,然后就能进行类型检查了。