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

React Native项目运行gradlew时settings.gradle报索引越界错误如何解决?

问题原因

报错指向settings.gradle第2行代码,这行的作用是通过node命令查找expo包的安装路径,String index out of range: 0本质是执行node命令返回了空字符串,trim后为空值,后续文件路径解析时触发了空字符串的索引越界。
常见触发场景有两个:

  • 系统找不到node命令:如果你是通过nvm、fnm这类Node版本管理工具安装的Node,Gradle运行时的shell环境没有加载对应的Node路径,导致node命令执行失败返回空。
  • 项目未安装expo依赖:node_modules中不存在expo包,require.resolve('expo/package.json')执行失败返回空。

前置排查:先确认你已经在项目根目录执行过包安装命令(npm install/yarn install/pnpm install),确保node_modules中存在expo相关依赖,且执行gradlew命令的路径是项目下的android/目录。

修复方案

方案1:临时生效(单次构建用)

执行gradlew命令前,先指定node的完整路径:

  1. 先在终端执行which node获取node的完整安装路径,示例输出为/Users/username/.nvm/versions/node/v18.18.0/bin/node
  2. 执行构建命令时加上NODE_BINARY变量,示例:
NODE_BINARY=/Users/username/.nvm/versions/node/v18.18.0/bin/node ./gradlew clean
NODE_BINARY=/Users/username/.nvm/versions/node/v18.18.0/bin/node ./gradlew bundleRelease

方案2:永久生效(本机固定环境)

在你常用的shell配置文件(比如~/.zshrc、~/.bashrc)末尾添加如下环境变量,替换为你自己的node路径:

export NODE_BINARY=$(which node)

添加后执行source ~/.zshrc(对应你实际使用的shell配置文件)生效,之后再执行gradlew命令无需额外配置。

方案3:项目级适配(适配所有开发人员)

修改android/settings.gradle文件的第2行,手动兼容node命令执行逻辑,把原来的第2行替换为如下代码:

def expoAutolinkingPath = new ByteArrayOutputStream()
exec {
    commandLine "node", "--print", "require.resolve('expo/package.json')"
    workingDir rootDir
    standardOutput = expoAutolinkingPath
}
apply from: new File(expoAutolinkingPath.toString().trim(), "../scripts/autolinking.gradle")

如果后续第5行的@react-native-community/cli相关代码也出现同类报错,可以用同样的逻辑修改。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 02:06:01