React Native升级后Gradle编译失败:Kotlin版本不兼容问题
React Native升级后Kotlin版本不兼容问题解决
问题
将React Native从0.72.5升级至0.74.2、Gradle从7.5.1升级到8.6后,Android构建失败,报错:react-native-gradle-plugin:compileKotlin任务执行失败,提示Kotlin元数据版本不兼容(实际1.9.0 vs 预期1.6.0)。
错误日志
The class is loaded from C:/Users/USER/.gradle/wrapper/dists/gradle-8.6-all/3mbtmo166bl6vumsh5k2lkq5h/gradle-8.6/lib/kotlin-stdlib-1.9.20.jar!/kotlin/collections/CollectionsKt__CollectionsKt.class e: C:\Users\USER\Downloads\picky_anu_anshif\picky_anu_anshif\node_modules\react-native-gradle-plugin\src\main\kotlin\com\facebook\react\utils\ProjectUtils.kt: (51, 48): Class 'kotlin.text.StringsKt__StringsKt' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.9.0, expected version is 1.6.0. The class is loaded from C:/Users/USER/.gradle/wrapper/dists/gradle-8.6-all/3mbtmo166bl6vumsh5k2lkq5h/gradle-8.6/lib/kotlin-stdlib-1.9.20.jar!/kotlin/collections/ArraysKt___ArraysKt.class FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':react-native-gradle-plugin:compileKotlin'.
根本原因
package.json中手动安装的react-native-gradle-plugin版本为0.71.19,与React Native 0.74.2版本不匹配。旧版本插件基于Kotlin 1.6编译,而Gradle 8.6自带的Kotlin标准库为1.9.20,版本冲突导致元数据不兼容。
解决方案
1. 移除手动安装的gradle插件依赖
编辑package.json,删除dependencies中的"react-native-gradle-plugin": "^0.71.19"。React Native 0.74.x会自动绑定对应版本的gradle插件,无需单独安装。
2. 修正Android构建配置
编辑android/build.gradle:
- 在文件最顶部添加RN版本变量,确保插件版本与RN核心版本对齐:
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) include ':app' ext.reactNativeVersion = "0.74.2" - 修改
buildscript中的插件引用,使用RN自带的对应版本:buildscript { ext { buildToolsVersion = "34.0.0" minSdkVersion = 26 compileSdkVersion = 34 targetSdkVersion = 34 ndkVersion = "26.1.10909125" kotlin_version = '1.9.22' // 此版本与Gradle 8.6兼容 } repositories { google() mavenCentral() } dependencies { classpath 'com.google.gms:google-services:4.3.15' classpath("com.android.tools.build:gradle") // 修改为自动匹配RN版本的插件引用 classpath("com.facebook.react:react-native-gradle-plugin") { version rootProject.ext.reactNativeVersion } classpath 'com.google.firebase:firebase-crashlytics-gradle:2.9.4' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath 'com.google.firebase:perf-plugin:1.4.2' } }
3. 清理缓存并重新构建
执行以下命令清理缓存并重新构建项目:
# 强制重新安装依赖 yarn install --force # 清理Android构建缓存 cd android && ./gradlew clean # 重新构建Android项目 cd .. && yarn android
验证
构建成功后,检查:react-native-gradle-plugin任务是否正常执行,确认Kotlin版本冲突问题已解决。
内容的提问来源于stack exchange,提问作者Anu Robinson
相关产品推荐
相关产品推荐

