如何正确使用react-native git子模块?相关依赖报错该如何解决?
React Native 公共函数 Git 子模块最佳实践
问题根因
- 第一个报错 Native Module not found:子模块内安装的
react-native-get-random-values包含原生代码,子模块独立 node_modules 中的原生依赖不会被主项目识别、自动链接,导致无法找到对应原生模块 - 第二个报错 Invariant Violation: Module RCTDeviceEventEmitter is not a registered callable module:子模块单独安装 react-native 后,运行时会加载主项目和子模块两份 react-native 实例,实例间状态不互通导致冲突
具体实施规则
1. 子模块 package.json 配置优化
子模块不要把 react-native、react-native-get-random-values、uuid 这类和宿主项目强相关的依赖放在 dependencies 里,全部移到 peerDependencies 中,开发阶段用到的同类依赖放在 devDependencies 即可,避免运行时出现多实例冲突,参考配置:
{ "name": "your-common-utils", "version": "1.0.0", "peerDependencies": { "react": ">=18.0.0", "react-native": ">=0.65.0", "uuid": "^9.0.0", "react-native-get-random-values": "^1.9.0" }, "devDependencies": { "react": "^18.2.0", "react-native": "^0.72.0", "uuid": "^9.0.0", "react-native-get-random-values": "^1.9.0", "@types/uuid": "^9.0.2" } }
2. 主项目侧依赖配置
主项目直接安装所有子模块声明的 peer 依赖即可:
npm install uuid react-native-get-random-values # 如果使用的 React Native 版本低于 0.60,需要额外执行手动链接 npx react-native link react-native-get-random-values
3. 代码适配
你现有子模块的 generateId 函数无需修改,运行时所有依赖会自动从主项目的 node_modules 加载,不会再出现依赖缺失或多实例冲突问题。
4. 可选体验优化
如果是 TS 项目,可以在主项目 tsconfig.json 中配置子模块引入别名,避免写过长的相对路径:
{ "compilerOptions": { "paths": { "@common/utils": ["./相对路径/子模块目录/index"] } } }
其他注意事项
- 子模块不要提交自身的 node_modules 文件夹,所有运行时依赖统一由主项目管理
- 如果后续子模块新增了包含原生代码的依赖,需要额外在主项目的 iOS Podfile、Android settings.gradle 中手动引入子模块内的原生代码路径
- 每次拉取子模块更新后,先检查子模块 peerDependencies 是否有变更,同步在主项目更新对应依赖版本即可
内容的提问来源于stack exchange,提问作者Praud
相关产品推荐
相关产品推荐

