Expo搭配Metro Bundler配置monorepo时外部模块无法解析react导入
解决方案
1. 补全metro.config.js的依赖别名配置
你当前只配置了共享模块目录的别名,没有指定react、react-native、@babel/runtime等公共依赖的解析路径,Metro解析外部模块的导入时会优先在外部模块所在目录的上层查找这些依赖,找不到就会抛出报错。你需要把这些公共依赖统一指向主Expo项目的node_modules:
const path = require('path'); // 定义主项目node_modules路径 const projectNodeModules = path.resolve(__dirname, './node_modules'); const extraNodeModules = { 'modules': path.resolve(__dirname, '../../modules'), // 补全公共依赖别名,统一使用主项目的依赖包 'react': path.resolve(projectNodeModules, 'react'), 'react-native': path.resolve(projectNodeModules, 'react-native'), '@babel/runtime': path.resolve(projectNodeModules, '@babel/runtime') }; const watchFolders = [ path.resolve(__dirname, '../../modules') ]; const nodeModulesPaths = [projectNodeModules]; module.exports = { transformer: { getTransformOptions: async () => ({ transform: { experimentalImportSupport: true, inlineRequires: true, }, }), }, resolver: { extraNodeModules, nodeModulesPaths, sourceExts: ['js', 'jsx', 'json', 'ts', 'tsx'] }, watchFolders };
2. 调整babel.config.js配置
默认Babel不会转译主项目根目录之外的代码,你需要把共享模块目录加入到转译白名单:
const path = require('path'); module.exports = function(api) { api.cache(true); return { presets: ['babel-preset-expo'], // 把外部共享模块目录加入转译范围 include: [ path.resolve(__dirname, '../../modules') ] }; };
3. 清理缓存重启服务
执行以下命令重启Metro避免缓存影响:
npx expo start --clear
如果仍报错可以同时删除主项目的node_modules和.lock文件后重新安装依赖。
内容的提问来源于stack exchange,提问作者Jim B.
相关产品推荐
相关产品推荐

