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

在Turborepo中运行Expo报错:无法从index.ts解析expo

Turborepo中Expo项目无法解析"expo"模块的解决方案

问题重现

执行pnpm dev启动Expo项目时,终端报错:

Unable to resolve "expo" from "index.ts"

模拟器内显示:

Unable to resolve module expo from /Users/xx/main/apps/expo/index.ts: expo could not be found within the project or in these directories:
  node_modules
  ../../node_modules
> 1 | import { registerRootComponent } from "expo";
    |                                        ^

已尝试删除所有node_modules、清理项目缓存,但问题依旧。

可能原因

Turborepo结合pnpm使用时,pnpm的硬链接依赖结构与npm/yarn不同,Metro默认的路径解析规则无法正确定位到expo包;同时当前Metro配置未适配pnpm的依赖布局。

解决方案

1. 确认Workspace配置

检查项目根目录的pnpm-workspace.yaml,确保Expo项目被包含在workspace中:

packages:
  - "apps/*"  # 根据实际项目路径调整
  - "packages/*"

2. 调整Metro配置适配pnpm

修改apps/expo/metro.config.js,添加pnpm专属依赖路径并启用package exports解析:

const { getDefaultConfig } = require("expo/metro-config");
const path = require("path");

const projectRoot = __dirname;
const workspaceRoot = path.resolve(projectRoot, "../..");

const config = getDefaultConfig(projectRoot);

// 保留原有配置
config.resolver.sourceExts.push("cjs");
config.watchFolders = [workspaceRoot];

// 适配pnpm的依赖结构,添加根目录的.pnpm路径
config.resolver.nodeModulesPaths = [
  path.resolve(projectRoot, "node_modules"),
  path.resolve(workspaceRoot, "node_modules"),
  path.resolve(workspaceRoot, ".pnpm"), // 新增:指向pnpm缓存依赖目录
];

// 禁用层级查找可能导致pnpm依赖无法解析,尝试注释或设为false
// config.resolver.disableHierarchicalLookup = true;

// 启用package exports规则,适配pnpm的包导出逻辑
config.resolver.unstable_enablePackageExports = true;

module.exports = config;

3. 配置pnpm依赖Hoist(可选)

在项目根目录创建或修改.npmrc,将Expo和React相关依赖Hoist到根目录,方便Metro查找:

hoist=true
hoist-pattern[]=expo*
hoist-pattern[]=react*
hoist-pattern[]=react-native*

4. 重新安装并清理缓存

在项目根目录执行以下命令:

# 重新安装所有依赖
pnpm install

# 清理Expo缓存并重启项目
npx expo start --clear

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 17:05:31