React Native开发中引入gun/lib/mobile.js遇依赖解析与Metro错误
React Native集成Gun.js遇到的依赖与Metro编译问题
问题场景
React Native开发中集成Gun.js时,使用以下代码:
import { REACT_APP_GUN_PEER } from "@env"; import "gun/lib/mobile.js" import Gun from "gun/gun"; import sea from "gun/sea"; import "gun/lib/radix.js"; import "gun/lib/radisk.js"; import "gun/lib/store.js"; import "gun/lib/rindexed.js"; import asyncStore from 'gun/lib/ras.js' import { storeLocalData } from "../Utils/utils"; import AsyncStorage from "@react-native-async-storage/async-storage"; Gun({ store: asyncStore({ AsyncStorage }) }) export const gun = new Gun(REACT_APP_GUN_PEER); // Gun relay export const SEA = sea; export const appDB = gun.get("ticTacToe"); export const createLocalUser = async (name) => { try { const pair = await SEA.pair(); const user = { name, pair, }; storeLocalData("user", user); } catch (e) { return e } }
错误1:导入gun/lib/mobile.js时
报错信息:
Unable to resolve "text-encoding" from "node_modules/gun/lib/mobile.js"
错误2:注释掉import "gun/lib/mobile.js"后
报错信息:
ERROR Error: Dynamic require defined at line 5; not supported by Metro, js engine: hermes ERROR Invariant Violation: "main" has not been registered. This can happen if: - Metro(本地开发服务器)在错误的文件夹中运行。检查Metro是否正在运行,停止并在当前项目中重启。 - 模块因错误加载失败,且未调用`AppRegistry.registerComponent`,js engine: hermes
解决方案
处理text-encoding依赖缺失
- 安装缺失依赖:
npm install text-encoding --save # 或使用yarn yarn add text-encoding
- 配置Metro解析该模块:
在项目根目录的metro.config.js中修改配置:
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config'); module.exports = mergeConfig(getDefaultConfig(__dirname), { resolver: { extraNodeModules: { 'text-encoding': require.resolve('text-encoding'), }, }, });
处理Metro不支持动态require问题
- 保留
import "gun/lib/mobile.js"导入,该模块是Gun针对移动端的适配,能规避核心模块中的动态require语法问题。 - 若仍有动态require报错,在
metro.config.js中补充配置:
module.exports = mergeConfig(getDefaultConfig(__dirname), { transformer: { allowJs: true, }, resolver: { extraNodeModules: { 'text-encoding': require.resolve('text-encoding'), }, }, });
- 清理缓存并重启Metro:
npx react-native start --reset-cache
内容的提问来源于stack exchange,提问作者Prashant Sakre
相关产品推荐
相关产品推荐

