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

Gradle 8.0环境下React Native项目构建报错求助

React Native构建失败:Gradle 8.0与Kotlin编译问题解决

问题描述

使用React Native模板运行应用时构建失败,已升级React Native至最新版本,但仍出现以下错误:

FAILURE: Build failed with an exception.

  • 问题原因:配置':expo'项目时出现问题。

Failed to notify project evaluation listener.
org.gradle.api.GradleException: Adding a Configuration as a dependency is no longer allowed as of Gradle 8.0.
KotlinJvmAndroidCompilation with name 'debug' not found.

项目配置文件

android/build.gradle

buildscript {
    ext {
        buildToolsVersion = "33.0.0"
        minSdkVersion = 21
        compileSdkVersion = 33
        targetSdkVersion = 33
        supportLibVersion = "33.0.0"
        googlePlayServicesAuthVersion = "16.0.1"
        kotlinVersion = "1.4.10"
    }
        repositories {
        google()
        mavenCentral()
        mavenCentral()
    }
    dependencies {
        // classpath 'com.android.tools.build:gradle:4.0.0'
        classpath("com.android.tools.build:gradle")
        classpath("com.facebook.react:react-native-gradle-plugin")
        classpath 'com.google.gms:google-services:4.2.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenCentral()
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }
        maven {
            // expo-camera bundles a custom com.google.android:cameraview
            url "$rootDir/../node_modules/expo-camera/android/maven"
        }
        maven { url 'https://maven.google.com' }
        maven { url 'https://www.jitpack.io' }

        google()
        jcenter()
    }
}

android/app/build.gradle

apply plugin: "com.android.application"
apply plugin: "com.facebook.react"

import com.android.build.OutputFile


project.ext.react = [
    enableHermes: false,  // clean and rebuild if changing
]

def enableSeparateBuildPerCPUArchitecture = false

def enableProguardInReleaseBuilds = false

def jscFlavor = 'org.webkit:android-jsc:+'

def reactNativeArchitectures() {
    def value = project.getProperties().get("reactNativeArchitectures")
    return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}


android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }


    dexOptions {
        javaMaxHeapSize "8g"
        jumboMode true
    }

    defaultConfig {
        applicationId "io.instamobile"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        vectorDrawables.useSupportLibrary = true
        missingDimensionStrategy 'react-native-camera', 'general'
        multiDexEnabled true
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }

    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }

        }
    }

    packagingOptions {
        pickFirst '**/armeabi-v7a/libc++_shared.so'
        pickFirst '**/x86/libc++_shared.so'
        pickFirst '**/arm64-v8a/libc++_shared.so'
        pickFirst '**/x86_64/libc++_shared.so'
        pickFirst '**/x86/libjsc.so'
        pickFirst '**/armeabi-v7a/libjsc.so'
    }
}

// apply from: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute().text.trim(), "../react.gradle")

dependencies {
    // The version of react-native is set by the React Native Gradle Plugin
    implementation("com.facebook.react:react-android")

    implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.0.0")

    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}")
    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}")

    //expo
    def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true";
    def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true";
    def isWebpAnimatedEnabled = (findProperty('expo.webp.animated') ?: "") == "true";

    // All fresco packages should use the same version
    if (isGifEnabled || isWebpEnabled) {
        implementation 'com.facebook.fresco:fresco:2.0.0'
        implementation 'com.facebook.fresco:imagepipeline-okhttp3:2.0.0'
    }

    if (isGifEnabled) {
        // For animated gif support
        implementation 'com.facebook.fresco:animated-gif:2.0.0'
    }

    if (isWebpEnabled) {
        // For webp support
        implementation 'com.facebook.fresco:webpsupport:2.0.0'
        if (isWebpAnimatedEnabled) {
            // Animated webp support
            implementation 'com.facebook.fresco:animated-webp:2.0.0'
        }
    }

    if (hermesEnabled) {
    implementation("com.facebook.react:hermes-engine:+") {
        exclude group: 'com.facebook.fbjni'
    }
    } else {
        implementation jscFlavor
    }
}

// Run this once to be able to run the application with BUCK
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.implementation
    into 'libs'
}
apply from: new File(["node", "--print", "require.resolve('@react-native-community/cli-platform-android/package.json')"].execute().text.trim(), "../native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply plugin: 'com.google.gms.google-services'

gradle-wrapper.properties

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

解决方案

1. 匹配Gradle与Android Gradle插件版本

Gradle 8.0.1需要对应版本的Android Gradle插件(AGP),修改android/build.gradle中buildscript的依赖:

classpath("com.android.tools.build:gradle:8.0.2") // 与Gradle 8.0.1兼容的版本

2. 升级Kotlin版本

旧版Kotlin(1.4.10)与Gradle 8.0不兼容,修改android/build.gradle里的kotlinVersion:

kotlinVersion = "1.8.20" // 适配AGP 8.0的稳定版本

3. 移除废弃的jcenter仓库

jcenter已停止服务,从android/build.gradle的allprojects.repositories中删除jcenter():

allprojects {
    repositories {
        mavenCentral()
        mavenLocal()
        maven { url("$rootDir/../node_modules/react-native/android") }
        maven { url("$rootDir/../node_modules/jsc-android/dist") }
        maven { url "$rootDir/../node_modules/expo-camera/android/maven" }
        maven { url 'https://maven.google.com' }
        maven { url 'https://www.jitpack.io' }
        google()
        // 移除jcenter()
    }
}

4. 修复Hermes依赖判断逻辑

android/app/build.gradle中hermesEnabled变量未定义,添加定义并从project.ext.react中读取配置:

// 在dependencies块之前添加
def hermesEnabled = project.ext.react.enableHermes

// 原有的Hermes判断部分保持不变
if (hermesEnabled) {
    implementation("com.facebook.react:hermes-engine:+") {
        exclude group: 'com.facebook.fbjni'
    }
} else {
    implementation jscFlavor
}

5. 清理缓存并重新构建

执行以下命令清理Gradle缓存并重新编译项目:

cd android
./gradlew clean
cd ..
npx react-native run-android

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 17:37:01