React+TypeScript组件库跨项目引用报错:无法找到模块rd-component
React+TypeScript组件库无法直接通过包名导入的问题解决
问题场景
使用npx create-react-app rd-component --template typescript创建React+TypeScript组件库,存放支付、登录、页脚等公共组件:
- 编写
src/component/demo/CommonPage.tsx组件:
import React from "react"; import { useDispatch, useSelector } from "react-redux"; const CommonPage = () => { const dispatch = useDispatch(); React.useEffect(() => { }, [dispatch]); return ( <div> </div> ); }; export default CommonPage;
- 在
src/index.tsx中导出组件:
import CommonPage from "../component/demo/CommonPage"; export { CommonPage }
- 将组件库打包为tgz文件后,在目标项目执行
npm install ~/source/reddwarf/frontend/rd-component/rd-component-0.1.0.tgz安装。尝试直接导入时:
import CommomPage from "rd-component";
出现错误:
Cannot find module 'rd-component' or its corresponding type declarations.ts(2307) No quick fixes available
但指定完整路径import CommomPage from "rd-component/src/component/demo/CommonPage";可正常使用,需解决配置遗漏问题。
解决步骤
1. 配置package.json入口与文件范围
在组件库的package.json中添加以下字段,明确包的入口和需要发布的文件:
{ "main": "build/index.js", "module": "build/index.esm.js", "types": "build/index.d.ts", "files": [ "build" ] }
main:指定CommonJS规范的入口文件;module:可选,指定ES模块入口,支持tree-shaking;types:指定TypeScript类型声明文件的位置;files:限定npm包包含的文件目录,避免冗余文件被打包。
2. 生成TypeScript类型声明
默认create-react-app不会自动生成类型声明,需修改组件库的tsconfig.json:
{ "compilerOptions": { "declaration": true, "declarationDir": "build", // 保留原有其他配置 } }
安装必要的类型依赖(若未安装):
npm install @types/react @types/react-redux --save-dev
执行npm run build,此时build目录会生成对应的.d.ts类型文件。
3. 修正导入方式与拼写错误
组件采用命名导出export { CommonPage },因此导入时需使用命名导入,同时修正拼写错误(CommomPage→CommonPage):
import { CommonPage } from "rd-component";
4. 重新打包并安装
完成上述配置后,重新执行npm run build生成新的打包产物,重新打包为tgz文件,在目标项目中重新安装即可正常通过包名导入组件。
可选优化:若需要更灵活的组件库打包配置,可替换
create-react-app为rollup或tsup这类专门的组件库打包工具,它们对类型生成、多格式输出支持更友好。
内容的提问来源于stack exchange,提问作者Dolphin
相关产品推荐
相关产品推荐

