web-dev-qa-db-fra.com

React Erreur de construction native: le texte ne doit pas être nul ou vide

Ma build Jenkins m'a donné l'erreur suivante:

13:18:22 FAILURE: Build failed with an exception.
13:18:22 
13:18:22 * Where:
13:18:22 Script '/Users/abcd/Jenkins/Jenkins-Workspaces/ABCD/ABCDL/node_modules/@react-native-community/cli-platform-Android/native_modules.gradle' line: 190
13:18:22 
13:18:22 * What went wrong:
13:18:22 A problem occurred evaluating settings 'AppName'.
13:18:22 > Text must not be null or empty
13:18:22 

Il semble que le problème soit avec le module de nœud @react-native-community/cli-platform, Mais en relisant ce problème fermé: https://github.com/facebook/react-native/issues/25479

ce n'est pas clair pour moi quelle est exactement la solution proposée et finale à cela.

Il y a une recommandation sur un correctif qui est plus simple dans ce problème réactif natif: https://github.com/facebook/react-native/issues/25822

mais mon erreur ne se plaint pas de cette ligne.

En ce qui concerne l'installation de @react-native-community/cli Je pense que je l'ai déjà dans mon fichier package-lock.json:

"react-native": {
      "version": "0.60.4",
      "resolved": "https://registry.npmjs.org/react-native/-/react-native-0.60.4.tgz",
      "integrity": "sha512-WE41lbGQjnzM9srIFtMDtMJkQAvk95iZwuFvAxl68s80bkYa7Ou9sGFHpeYIV6cY8yHtheCSo5q6YMxhdfkdOw==",
      "requires": {
        "@babel/runtime": "^7.0.0",
        "@react-native-community/cli": "^2.0.1",
        "@react-native-community/cli-platform-Android": "^2.0.1",
        "@react-native-community/cli-platform-ios": "^2.0.1",

D'autres ont mentionné quelque chose à propos de app/build.gradle, Voici la partie pertinente de la mienne:

// Run this once to be able to run the application with BUCK
// 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)

Il a également été fait mention de Android/settings.gradle, Celui-ci est le mien:

rootProject.name = 'NFIBEngage'
include ':react-native-device-info'
project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/Android')
include ':appcenter-crashes'
project(':appcenter-crashes').projectDir = new File(rootProject.projectDir, '../node_modules/appcenter-crashes/Android')
include ':appcenter-analytics'
project(':appcenter-analytics').projectDir = new File(rootProject.projectDir, '../node_modules/appcenter-analytics/Android')
include ':appcenter'
project(':appcenter').projectDir = new File(rootProject.projectDir, '../node_modules/appcenter/Android')
include ':react-native-webview'
project(':react-native-webview').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-webview/Android')
apply from: file("../node_modules/@react-native-community/cli-platform-Android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'

D'après ce que j'ai rassemblé ici:

https://react-native-community.github.io/upgrade-helper/?from=0.53.3&to=0.60.4

Les fichiers ci-dessus sont corrects.

Alors, qu'est-ce qui ne va pas exactement ici et comment puis-je le réparer?

En termes de node_modules/@react-native-community/cli-platform-Android/native_modules.gradle line 190 Est celui-ci:

def json = new JsonSlurper().parseText(reactNativeConfigOutput)

Le problème pourrait-il être avec la façon dont j'ai écrit le fichier index.js:

/**
 * @format
 */

import { AppRegistry } from "react-native";
// old config code
import KeyboardManager from "react-native-keyboard-manager";
// old config code ^^^
import NFIBEngage from "./App";
import { name as appName } from "./app.json";

// old config code
import { Sentry } from "react-native-sentry";

Sentry.config(
  "https://[email protected]/123456677"
).install();

KeyboardManager.setToolbarPreviousNextButtonEnable(true);
// old config code ^^^

AppRegistry.registerComponent("NFIBEngage", () => NFIBEngage);

AppRegistry.registerComponent() est-elle écrite correctement?

J'ai exécuté le script Jenkins localement, ce qui, je crois, est ce script ici:

import fs from "fs-extra";
import eachSeries from "async/eachSeries";
import { exec } from "child_process";
import { androidDirectory } from "../../app.json";
import { resolveFromRoot, distDir, createLogger } from "../build";

const logger = createLogger("Android");

const APK_PATTERN = /release\.apk$/i;

function copyArtifactsToDist() {
  logger.logHeader("Copying APK to Dist", { repeatChar: "=" });
  const baseDir = `${androidDirectory}/app/build/outputs/apk`;

  const allFlavs = ["dev", "qa", "ua", "prod"];
  const branchName = process.env.GitVersion_BranchName || "";
  const buildFlavour = branchName.startsWith("release/") ? allFlavs : ["dev"];
  const envs = {
    dev: "INT",
    qa: "QA",
    ua: "UA",
    prod: ""
  };

  buildFlavour
    .map(env => {
      const apkOutputDir = resolveFromRoot(`${baseDir}/${env}/release`);
      return {
        apkOutputDir,
        env
      };
    })
    .forEach(({ apkOutputDir, env }) => {
      const src = `${apkOutputDir}/app-${env}-release.apk`;
      //prettier-ignore
      const binaryName = env === 'prod' ? 'ENGAL.apk' : `ENGAL-${envs[env]}.apk`;
      const dest = `${distDir}/${binaryName}`;
      fs.copy(src, dest, (err: Error) => {
        if (err) {
          logger.error(err);
        }
      });
    });
}

function run() {
  logger.logHeader("Starting Android Builds", { repeatChar: "#" });
  const flavours = [
    {
      endpoint: "dv",
      flavour: "Dev",
      appcenterKey: "<hashKeys>"
    },
    {
      endpoint: "qa",
      flavour: "Qa",
      appcenterKey: "<hashKeys>"
    },
    {
      endpoint: "ua",
      flavour: "Ua",
      appcenterKey: "<hashKeys>"
    },
    {
      endpoint: "prod",
      flavour: "Prod",
      appcenterKey: "<hashKeys>"
    }
  ];

  const versionCode = process.env.Build || 1;
  const release = process.env.GitVersion_MajorMinorPatch || "1.0.0";
  const fullAppVersion = `${release}-${versionCode}`;

  const devFlav = flavours.find(f => f.flavour.toLocaleLowerCase() === "dev");

  const branchName = process.env.GitVersion_BranchName || "";
  const buildFlavour = branchName.startsWith("release/") ? flavours : [devFlav];

  eachSeries(
    buildFlavour,
    (f, callback) => {
      //prettier-ignore
      logger.logHeader(
        `starting gradle assemble${f.flavour}Release with flag - versionName=${fullAppVersion} -PversionCode=${versionCode}`,
        {repeatChar: '-'}
      );

      const engaInfo = `ENGAGE_VERSION=${fullAppVersion}`;
      const engaEndpoint = `ENGAGE_ENDPOINT=${f.endpoint}`;
      const engaCenter = `APPCENTER_KEY=${f.appcenterKey}`;
      const engaPlatform = "APPCENTER_PLATFORM=Android";
      //prettier-ignore
      const prepare = `${engaEndpoint} ${engaCenter} ${engaInfo} ${engaPlatform} npm run setup`;
      const cd = `cd ${androidDirectory}`;
      //prettier-ignore
      const releaseCmd = `./gradlew assemble${f.flavour}Release -PversionName=${fullAppVersion} -PversionCode=${versionCode} && cd ..`;

      exec(`${prepare} && ${cd} && ${releaseCmd}`, err => {
        if (err) {
          return callback(err);
        }

        logger.logHeader(`${f.flavour} Android Build Successful!`, {
          repeatChar: "#"
        });
        logger.close();
        callback(null);
      });
    },
    error => {
      if (error) {
        logger.logHeader("Android Builds Failed!", {
          repeatChar: "#"
        });
        logger.error(error);
        logger.close();
      }
      copyArtifactsToDist();
    }
  );
}

run();

via npm run build et localement j'ai eu cette erreur:

FAILURE: Build failed with an exception.

* What went wrong:
Task 'assembleDevRelease' not found in root project 'AppName'. Some candidates are: 'assembleRelease'.

S'agit-il d'erreurs liées? Toute personne expérimentée avec React Builds natifs?

Comme suggéré, j'ai cherché dans mon fichier Android/app/build.gradle Pour productFlavors et j'ai remarqué qu'en effet ils manquaient entre ici:

buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://facebook.github.io/react-native/docs/signed-apk-Android.
            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 as described here:
            // https://developer.Android.com/studio/build/configure-apk-splits.html
            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) * 123456 + defaultConfig.versionCode
            }

        }
    }

Je l'ai donc ajouté comme ceci:

buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://facebook.github.io/react-native/docs/signed-apk-Android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-Android.txt"), "proguard-rules.pro"
        }
    }

    productFlavors {
      dev {
        resValue "string", "app_name", getAppName("INT")
        resValue "string", "link_launcher", getLauncher("dv")
        applicationIdSuffix ".dv"
        manifestPlaceholders = [onesignal_app_id: "<hash_id>",
                                onesignal_google_project_number: "123456789"]
      }
      qa {
        resValue "string", "app_name", getAppName("QA")
        resValue "string", "link_launcher", getLauncher("qa")
        applicationIdSuffix ".qa"
        manifestPlaceholders = [onesignal_app_id: "<hash_id>",
                                onesignal_google_project_number: "123456789"]
      }
      ua {
        resValue "string", "app_name", getAppName("UA")
        resValue "string", "link_launcher", getLauncher("ua")
        applicationIdSuffix ".ua"
        manifestPlaceholders = [onesignal_app_id: "<hash_id>",
                                onesignal_google_project_number: "123456789"]
      }
      prod {
        resValue "string", "app_name", getAppName()
        resValue "string", "link_launcher", getLauncher()
        manifestPlaceholders = [onesignal_app_id: "<hash_id>",
                                onesignal_google_project_number: "601125149914"]
      }
    }

    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.Android.com/studio/build/configure-apk-splits.html
            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
            }

        }
    }

Le buildTypes est un peu différent de l'héritage d'origine buildTypes donc je ne sais pas si ça va, mais en tout cas j'ai ensuite exécuté npm run build À nouveau localement et j'ai eu cette erreur :

* Where:
Build file '/Users/danale/Projects/NFIBEngage/Android/app/build.gradle' line: 168

* What went wrong:
A problem occurred evaluating project ':app'.
> Could not find method getAppName() for arguments [INT] on ProductFlavor_Decorated{name=dev, dimension=null, minSdkVersion=null, targetSdkVersion=null, renderscriptTargetApi=null, renderscriptSupportModeEnabled=null, renderscriptSupportModeBlasEnabled=null, renderscriptNdkModeEnabled=null, versionCode=null, versionName=null, applicationId=null, testApplicationId=null, testInstrumentationRunner=null, testInstrumentationRunnerArguments={}, testHandleProfiling=null, testFunctionalTest=null, signingConfig=null, resConfig=null, mBuildConfigFields={}, mResValues={}, mProguardFiles=[], mConsumerProguardFiles=[], mManifestPlaceholders={}, mWearAppUnbundled=null} of type com.Android.build.gradle.internal.dsl.ProductFlavor.

J'ai pu résoudre l'erreur locale en ajoutant les méthodes manquantes comme ceci:

def appName = "Engage";

/**
 * Get the version name from command line param
 *
 * @return int If the param -PversionName is present then return int value or -1
 */
def getAppName = { env ->
  return (env ? appName + " ("+ env + ")" : appName);
}

/**
 * Get the version name from command line param
 *
 * @return int If the param -PversionName is present then return int value or -1
 */
def getLauncher = { env ->
    return (env ? "engage-" + env + ".nfib.org" : "engage.nfib.org");
}

Android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    flavorDimensions "default"

    defaultConfig {
        applicationId "com.nfib.engage"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
    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.
            // see https://facebook.github.io/react-native/docs/signed-apk-Android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-Android.txt"), "proguard-rules.pro"
        }
    }

    productFlavors {
      dev {
        dimension 'default'
        resValue "string", "app_name", getAppName("INT")
        resValue "string", "link_launcher", getLauncher("dv")
        applicationIdSuffix ".dv"
        manifestPlaceholders = [onesignal_app_id: "b78285eb-f1ec-46f3-9ad0-c7efe691a401",
                                onesignal_google_project_number: "584236827312"]
      }
      qa {
        dimension 'default'
        resValue "string", "app_name", getAppName("QA")
        resValue "string", "link_launcher", getLauncher("qa")
        applicationIdSuffix ".qa"
        manifestPlaceholders = [onesignal_app_id: "e4280f5e-62ec-41a4-bd86-f5b94e471a36",
                                onesignal_google_project_number: "162802054510"]
      }
      ua {
        dimension 'default'
        resValue "string", "app_name", getAppName("UA")
        resValue "string", "link_launcher", getLauncher("ua")
        applicationIdSuffix ".ua"
        manifestPlaceholders = [onesignal_app_id: "2ffd8dc0-9c6b-4035-999d-fc694194725a",
                                onesignal_google_project_number: "594905904045"]
      }
      prod {
        dimension 'default'
        resValue "string", "app_name", getAppName()
        resValue "string", "link_launcher", getLauncher()
        manifestPlaceholders = [onesignal_app_id: "82dcb42f-1d35-4b79-bc28-2d1d02dbda36",
                                onesignal_google_project_number: "601125149914"]
      }
    }

Malheureusement, je continue à obtenir la même erreur dans Jenkins.

7
Daniel

J'ai aussi fait face à ce problème

solution très simple pour ce problème

Supprimer node_module

et

Réinstaller node_module: npm install

réagir-natif exécuter-Android

0
ANKIT-DETROJA

J'ai mis à niveau ma version de nœud sur mon outil CI et corrigé cette erreur exacte. J'étais auparavant sur la version 6 et je suis passé à 10

0
Vincent Vella