Интеграция Appcenter с Codepush. Невозможно добавить задачу «bundleDebugJsAndAssets», так как задача с таким именем уже существует

Действия по воспроизведению

  1. yarn add react-native-codepush
  2. Добавить следующее в android/app/build.gradle
apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"
  1. Добавить следующее в MainApplication.java
...
import com.microsoft.codepush.react.CodePush;
...
        @Override
        protected String getJSBundleFile() {
            return CodePush.getJSBundleFile();
        }
  1. Добавьте следующее в strings.xml
    <string name="CodePushDeploymentKey" moduleConfig="true">MYKEY</string>

Ожидаемое поведение

Сборка должна пройти успешно

Фактическое поведение

Что на самом деле происходит?

 $ react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 998 file(s) to forward-jetify. Using 4 workers...
info JS server already running.
info Installing the app...

> Configure project :app
WARNING: BuildType(debug): resValue 'react_native_dev_server_port' value is being replaced: 8081 -> 8081
WARNING: BuildType(debug): resValue 'react_native_inspector_proxy_port' value is being replaced: 8081 -> 8081
WARNING: BuildType(release): resValue 'react_native_dev_server_port' value is being replaced: 8081 -> 8081
WARNING: BuildType(release): resValue 'react_native_inspector_proxy_port' value is being replaced: 8081 -> 8081

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.0.1/userguide/command_line_interface.html#sec:command_line_warnings

FAILURE: Build failed with an exception.

* Where:
Script '/Users/user/Desktop/project/app/native/node_modules/react-native/react.gradle' line: 118

* What went wrong:
A problem occurred configuring project ':app'.
> Cannot add task 'bundleDebugJsAndAssets' as a task with that name already exists.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 4s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Run CLI with --verbose flag for more details.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

* Where:
Script '/Users/user/Desktop/project/app/native/node_modules/react-native/react.gradle' line: 118

* What went wrong:
A problem occurred configuring project ':app'.
> Cannot add task 'bundleDebugJsAndAssets' as a task with that name already exists.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 4s

    at makeError (/Users/user/Desktop/project/app/native/node_modules/execa/index.js:174:9)
    at /Users/user/Desktop/project/app/native/node_modules/execa/index.js:278:16
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async runOnAllDevices (/Users/user/Desktop/project/app/native/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:94:5)
    at async Command.handleAction (/Users/user/Desktop/project/app/native/node_modules/@react-native-community/cli/build/index.js:186:9)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Окружающая среда

  • версия с ответом на собственный код: ^ 6.2.1
  • реактивная версия: 0.62.2
  • Версия iOS/Android/Windows: неизвестно
  • Воспроизводится ли это в сборке отладки или сборке выпуска? проверяется только при отладке
  • Это воспроизводится на симуляторе или только на физическом устройстве? ошибка сборки

Внешние SDK

У меня есть внешний SDK в build.gradle. Я не знаю, является ли это причиной этой ошибки.

buildscript {
    repositories {
        maven { url 'https://plugins.gradle.org/m2/' } // Gradle Plugin Portal
    }
    dependencies {
        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.6, 0.99.99]'
    }
}

apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
apply plugin: "com.android.application"
apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"

....
apply plugin: 'com.google.gms.google-services'

Что я пробовал.

Я переместил два объявления в конец app/build.gradle. но ошибка остается той же

// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"

В некоторых статьях говорится об удалении строки apply from: "../../node_modules/react-native/react.gradle". Но новая ошибка

yarn run v1.22.4
$ react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 998 file(s) to forward-jetify. Using 4 workers...
info JS server already running.
info Installing the app...

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.0.1/userguide/command_line_interface.html#sec:command_line_warnings

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:mergeDebugAssets'.
> Could not resolve all task dependencies for configuration ':app:debugRuntimeClasspath'.
   > Could not resolve project :react-native-code-push.
     Required by:
         project :app
      > Unable to find a matching configuration of project :react-native-code-push:
          - None of the consumable configurations have attributes.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 3s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Run CLI with --verbose flag for more details.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:mergeDebugAssets'.
> Could not resolve all task dependencies for configuration ':app:debugRuntimeClasspath'.
   > Could not resolve project :react-native-code-push.
     Required by:
         project :app
      > Unable to find a matching configuration of project :react-native-code-push:
          - None of the consumable configurations have attributes.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 3s

    at makeError (/Users/user/Desktop/project/app/native/node_modules/execa/index.js:174:9)
    at /Users/user/Desktop/project/app/native/node_modules/execa/index.js:278:16
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async runOnAllDevices (/Users/user/Desktop/project/app/native/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:94:5)
    at async Command.handleAction (/Users/user/Desktop/project/app/native/node_modules/@react-native-community/cli/build/index.js:186:9)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Я удалил обе строки (которые на самом деле не имеют никакого смысла), ошибка

yarn run v1.22.4
$ react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 998 file(s) to forward-jetify. Using 4 workers...
info JS server already running.
info Installing the app...

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.0.1/userguide/command_line_interface.html#sec:command_line_warnings

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> Could not resolve all task dependencies for configuration ':app:debugCompileClasspath'.
   > Could not resolve project :react-native-code-push.
     Required by:
         project :app
      > Unable to find a matching configuration of project :react-native-code-push:
          - None of the consumable configurations have attributes.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 4s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Run CLI with --verbose flag for more details.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> Could not resolve all task dependencies for configuration ':app:debugCompileClasspath'.
   > Could not resolve project :react-native-code-push.
     Required by:
         project :app
      > Unable to find a matching configuration of project :react-native-code-push:
          - None of the consumable configurations have attributes.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 4s

    at makeError (/Users/user/Desktop/project/app/native/node_modules/execa/index.js:174:9)
    at /Users/user/Desktop/project/app/native/node_modules/execa/index.js:278:16
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async runOnAllDevices (/Users/user/Desktop/project/app/native/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:94:5)
    at async Command.handleAction (/Users/user/Desktop/project/app/native/node_modules/@react-native-community/cli/build/index.js:186:9)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.


person Faisal Manzer    schedule 08.06.2020    source источник
comment
И да, я много раз пытался очистить градуировку.   -  person Faisal Manzer    schedule 08.06.2020
comment
это голова, чтобы сказать, где реальная проблема. можете ли вы добавить воспроизводимый репозиторий git, чтобы я мог исправить ошибку для вас   -  person Muhammad Numan    schedule 10.06.2020
comment
Вы пытались запустить cli с флагом --verbose для получения более подробной информации?   -  person Saamer    schedule 11.06.2020


Ответы (4)


На самом деле ошибок было две:

  1. На самом деле в android/app/build.gradle есть строка, которая является apply from: "../../node_modules/react-native/react.gradle". Вам не нужно добавлять эту строку, вместо этого вам нужно добавить apply from: "../../node_modules/react-native-code-push/android/codepush.gradle" под ней. Добавление этого в конец может решить проблему для некоторых пользователей, но не для всех. Добавьте его в соответствующее место.

  2. Если есть ошибка gradle, это связано с multidex. Включите мультидекс для всей поддержки. Добавьте multiDexEnable true в android > defaultConfig. См. это для справки https://developer.android.com/studio/build/multidex#mdex-gradle

person Faisal Manzer    schedule 12.06.2020

Я тоже столкнулся с той же проблемой.

"react-native-code-push": "^6.2.1",
"react-native": "0.61.4",

Наконец, я удалил указанную вами строку, и она успешно построена. Я разместил в нижней части build.gradle

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
//apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"
person landorid    schedule 11.06.2020

У меня была такая же проблема, и я расскажу здесь всем, у кого есть то же самое, что и у меня. Оказывается, я не точно следовал инструкции.

Это также дало мне эту ошибку:

cannot find symbol
        new CodePush(getResources().getString(R.string.CodePushDeploymentKey), getApplicationContext(), BuildConfig.DEBUG)

Я использовал множественный -deployment-testing-android.md, чтобы использовать промежуточный и рабочий ключи. Меня смутила часть, в которой говорилось, что нужно добавить ваши ключи в файл android/app/build.gradle под buildTypes. При открытии этого файла там уже был только release, поэтому я добавил только раздел releaseStaging. Оказывается, вам также нужно добавить debug, даже если его еще не было. Решил это для меня.

person John Harding    schedule 29.06.2020

применить из: "../../node_modules/react-native/react.gradle" определено ранее, так что это просто дублирование, попробуйте прокомментировать или удалить его, и вы готовы к работе.

person arash peymanfar    schedule 27.06.2021