You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 07:45:06