React Native Android 依赖问题解决
当 React Native 团队发布新版本时,可能导致未更新的项目出现 Android 构建失败。本文将深入剖析问题根源并提供多种修复方案。
问题现象
当您的代码未做任何改动时,Android 构建突然失败并出现以下关键错误信息:
FAILURE: Build failed with an exception.
* Where: Build file '.../android/build.gradle' line: 115
* What went wrong:
> Could not resolve com.facebook.react:react-native:+.
> Cannot choose between the following variants of com.facebook.react:react-native:0.71.0-rc.0:
- debugVariantDefaultRuntimePublication
- releaseVariantDefaultRuntimePublication
根本原因
React Native 0.71.0-rc.0 发布后:
- 新版本被发布到 Maven Central 公共仓库
- 第三方库的依赖声明
implementation 'com.facebook.react:react-native:+'
会优先获取最新版 - 导致 gradle 获取远程版本而非本地
node_modules
版本 - 造成版本冲突和构建失败
🔧 永久解决方案
方法 1:添加仓库排他规则(推荐)
在 android/build.gradle
文件中更新 allprojects.repositories
配置:
buildscript {
// 保持您原有的配置
}
allprojects {
repositories {
// 🔒 添加排他规则,强制从 node_modules 获取 React Native
exclusiveContent {
filter { includeGroup "com.facebook.react" }
forRepository {
maven { url "$rootDir/../node_modules/react-native/android" }
}
}
// 原有仓库配置
google()
mavenCentral()
// ...
}
}
效果说明
此规则确保当包含 com.facebook.react
依赖时:
- 只查询
node_modules/react-native/android
仓库 - 完全忽略 Maven Central 中的 React Native 版本
- 彻底避免远程仓库版本覆盖本地版本的风险
方法 2:强制指定版本号
如果您的 gradle 版本不支持 exclusiveContent
,可改用在 android/build.gradle
添加:
// 自动获取项目中 react-native 的实际版本
def REACT_NATIVE_VERSION = new File(['node', '--print', "JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version"].execute(null, rootDir).text.trim())
allprojects {
configurations.all {
resolutionStrategy {
// 强制使用当前项目的 React Native 版本
force "com.facebook.react:react-native:" + REACT_NATIVE_VERSION
}
}
}
Kotlin 兼容性注意
若项目使用旧版 React Native:
- RN 0.68+ 开始使用 Kotlin 1.6.10
- 版本冲突可能导致 Kotlin 元数据错误
- 此时方法1/2 同时解决了 Kotlin 版本兼容问题
🚀 官方补丁升级(替代方案)
React Native 团队已为多个版本发布补丁:
原始版本 | 修复版本 |
---|---|
0.63.x | 0.63.5 |
0.64.x | 0.64.4 |
0.65.x | 0.65.2 |
0.66.x | 0.66.5 |
0.67.x | 0.67.5 |
0.68.x | 0.68.8 |
0.69.x | 0.69.11 |
0.70.x | 0.70.7 |
升级命令示例:
npm install react-native@0.70.7
升级步骤建议
- 在 package.json 中固定版本号
- 删除
node_modules
和package-lock.json
- 执行
npm install
- 运行
cd android && ./gradlew clean
构建验证与清理
应用修复后执行以下命令验证:
# 清理构建缓存
cd android && ./gradlew clean
# 重新启动 Metro 服务
npx react-native start --reset-cache
# 重新构建 Android 应用
npx react-native run-android
常见误操作排查
无效措施提醒
以下操作不能解决此问题:
- 删除
android/app/src/main/assets/index.android.bundle
- 修改
android/build.gradle
中的versionName
- 更改项目代码或资源文件
永久工程实践建议
在 所有第三方库 中替换
implementation 'com.facebook.react:react-native:+'
推荐明确指定版本:implementation 'com.facebook.react:react-native:0.XX.X'
定期检查项目中的
+
通配符依赖声明使用 react-native-upgrade-helper 管理版本升级
官方问题跟踪链接:facebook/react-native #35210