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

如何在Turborepo中使用共享React Native代码并解决依赖解析问题

解决Turborepo + React Native新架构中@babel/runtime无法解析的问题

针对你用Turborepo重构React Native新架构应用时,引入本地native-ui包后出现的@babel/runtime解析错误,以下是几个有效的解决步骤:

1. 统一安装@babel/runtime

  • 在项目根目录执行 pnpm add -D @babel/runtime,将依赖提升到根目录,确保所有工作区都能访问到
  • 或者在native-ui包目录执行 pnpm add @babel/runtime,把依赖作为该包的直接依赖而非开发依赖(React Native运行时需要此依赖)

2. 调整Metro配置

在App1的metro.config.js中,除了unstable_enableSymlinks,还需补充以下配置:

const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
const path = require('path');

const config = {};
const defaultConfig = getDefaultConfig(__dirname);

// 让Metro监听工作区根目录和native-ui包
defaultConfig.watchFolders = [
  path.resolve(__dirname, '../../'),
  path.resolve(__dirname, '../../packages/native-ui'),
];

// 指定@babel/runtime的解析路径
defaultConfig.resolver.extraNodeModules = {
  '@babel/runtime': path.resolve(__dirname, '../../node_modules/@babel/runtime'),
};

defaultConfig.resolver.unstable_enableSymlinks = true;

module.exports = mergeConfig(defaultConfig, config);

3. 检查pnpm的hoisting配置

在项目根目录的.npmrc文件中添加以下配置,确保@babel相关依赖能被正确提升:

hoist=true
public-hoist-pattern[]=@babel/*

4. 清除缓存并重启服务

  • 清除Metro缓存:pnpm cache clean && rm -rf node_modules/.cache/metro
  • 进入App1目录重装依赖:cd apps/App1 && rm -rf node_modules && pnpm install
  • 重置缓存重启Metro:pnpm start --reset-cache

额外注意事项

  • 确认native-ui的package.json中,main或exports字段指向正确的入口文件(比如src/index.tsx)
  • 若使用React Native新架构,确保native-ui包的Babel编译配置完整,没有遗漏必要的转译步骤

内容的提问来源于stack exchange,提问作者TheWhiteFang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 11:24:51