React Native 构建错误:文本不得为 null 或为空 [英] React Native build error: Text must not be null or empty

查看:63
本文介绍了React Native 构建错误:文本不得为 null 或为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Jenkins 构建给了我以下错误:

13:18:22 FAILURE:构建失败,出现异常.13:18:2213:18:22 * 其中:13:18:22 脚本/Users/abcd/Jenkins/Jenkins-Workspaces/ABCD/ABCDL/node_modules/@react-native-community/cli-platform-android/native_modules.gradle"行:19013:18:2213:18:22 * 出了什么问题:13:18:22 评估设置AppName"时出现问题.13:18:22 >文本不得为 null 或为空13:18:22

问题似乎出在 @react-native-community/cli-platform 节点模块上,但请仔细阅读这个已关闭的问题:https://github.com/facebook/react-native/issues/25479

我不清楚对此提出的和最终的解决方案究竟是什么.

在这个 react-native 问题中,有一个更直接的修复建议:https://github.com/facebook/react-native/issues/25822

但我的错误不是抱怨那条线.

至于安装 @react-native-community/cli 我相信我已经在我的 package-lock.json 文件中安装了它:

反应原生":{版本":0.60.4",已解决":https://registry.npmjs.org/react-native/-/react-native-0.60.4.tgz",完整性":sha512-WE41lbGQjnzM9srIFtMDtMJkQAvk95iZwuFvAxl68s80bkYa7Ou9sGFHpeYIV6cY8yHtheCSo5q6YMxhdfkdOw==",需要":{@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",

其他人提到了一些关于app/build.gradle的内容,这是我的相关部分:

//运行一次即可使用 BUCK 运行应用程序//将所有编译依赖项放入文件夹 libs 以供 BUCK 使用任务 copyDownloadableDepsToLibs(类型:复制){从configuration.compile进入库"}申请自:文件(../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle");applyNativeModulesAppBuildGradle(项目)

还提到了android/settings.gradle,这是我的:

rootProject.name = 'NFIBEngage'包括 ':react-native-device-info'project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/android')包括:appcenter-crashes"project(':appcenter-crashes').projectDir = new File(rootProject.projectDir, '../node_modules/appcenter-crashes/android')包括:appcenter-analytics"project(':appcenter-analytics').projectDir = new File(rootProject.projectDir, '../node_modules/appcenter-analytics/android')包括:应用中心"project(':appcenter').projectDir = new File(rootProject.projectDir, '../node_modules/appcenter/android')包括 ':react-native-webview'project(':react-native-webview').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-webview/android')申请自:文件(../node_modules/@react-native-community/cli-platform-android/native_modules.gradle");applyNativeModulesSettingsGradle(settings)包括':app'

根据我在这里收集的信息:

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

以上文件都是正确的.

那么这里到底有什么问题,我该如何解决?

node_modules/@react-native-community/cli-platform-android/native_modules.gradle line 190 而言,是这个:

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

问题可能出在我编写 index.js 文件的方式上:

/*** @格式*/import { AppRegistry } from react-native";//旧的配置代码从react-native-keyboard-manager"导入键盘管理器;//旧的配置代码 ^^^从./App"导入 NFIBEngage;从./app.json"导入 { name as appName };//旧的配置代码import { Sentry } from react-native-sentry";哨兵.config(https://asdf@sentry.io/123456677").安装();KeyboardManager.setToolbarPreviousNextButtonEnable(true);//旧的配置代码 ^^^AppRegistry.registerComponent(NFIBEngage", () => NFIBEngage);

AppRegistry.registerComponent() 写对了吗?

我在本地运行了 Jenkins 脚本,我相信这里就是这个脚本:

从fs-extra"导入fs;从async/eachSeries"导入 eachSeries;从child_process"导入 { exec };从../../app.json"导入{androidDirectory};import { resolveFromRoot, distDir, createLogger } from "../build";const logger = createLogger(android");const APK_PATTERN =/release\.apk$/i;函数 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 : [开发"];常量环境 = {开发:INT",qa: "QA",ua: UA",prod:"};构建风味.map(env => {const apkOutputDir = resolveFromRoot(`${baseDir}/${env}/release`);返回 {apk输出目录,环境};}).forEach(({ apkOutputDir, env }) => {const src = `${apkOutputDir}/app-${env}-release.apk`;//更漂亮的忽略const binaryName = env === 'prod' ?'ENGAL.apk':`ENGAL-${envs[env]}.apk`;const dest = `${distDir}/${binaryName}`;fs.copy(src, dest, (err: Error) => {如果(错误){记录器错误(错误);}});});}函数运行(){logger.logHeader(启动Android构建",{repeatChar:#"});常量口味 = [{端点:dv",风味:开发",appcenterKey: <hashKeys>>},{端点:qa",风味:Qa",appcenterKey: <hashKeys>>},{端点:ua",风味:Ua",appcenterKey: <hashKeys>>},{端点:产品",风味:产品",appcenterKey: <hashKeys>>}];const versionCode = process.env.Build ||1;const release = process.env.GitVersion_MajorMinorPatch ||1.0.0";const fullAppVersion = `${release}-${versionCode}`;const devFlav = flavors.find(f => f.flavor.toLocaleLowerCase() === "dev");const branchName = process.env.GitVersion_BranchName ||";const buildFlavour = branchName.startsWith("release/") ?口味:[devFlav];每个系列(构建风味,(f, 回调) =>{//更漂亮的忽略logger.logHeader(`开始 gradle assemble${f.flavor}Release with flag - versionName=${fullAppVersion} -PversionCode=${versionCode}`,{重复字符:'-'});const engaInfo = `ENGAGE_VERSION=${fullAppVersion}`;const engaEndpoint = `ENGAGE_ENDPOINT=${f.endpoint}`;const engaCenter = `APPCENTER_KEY=${f.appcenterKey}`;const engaPlatform = "APPCENTER_PLATFORM=android";//更漂亮的忽略const prepare = `${engaEndpoint} ${engaCenter} ${engaInfo} ${engaPlatform} npm run setup`;const cd = `cd ${androidDirectory}`;//更漂亮的忽略const releaseCmd = `./gradlew assemble${f.flavour}Release -PversionName=${fullAppVersion} -PversionCode=${versionCode} &&cd ..`;exec(`${prepare} && ${cd} && ${releaseCmd}`, err => {如果(错误){返回回调(错误);}logger.logHeader(`${f.flavor} Android 构建成功!`, {重复字符:#"});logger.close();回调(空);});},错误 =>{如果(错误){logger.logHeader(Android 构建失败!", {重复字符:#"});logger.error(error);logger.close();}copyArtifactsToDist();});}跑();

通过 npm run build 和本地我得到这个错误:

FAILURE:构建失败,出现异常.* 什么地方出了错:在根项目AppName"中找不到任务assembleDevRelease".一些候选是:'assembleRelease'.

这些是相关错误吗?有人在 React Native 构建方面有经验吗?

按照建议,我查看了 productFlavorsandroid/app/build.gradle 文件,并注意到它们之间确实丢失了:

buildTypes {调试{签名配置signingConfigs.debug}释放 {//注意!在生产中,您需要生成自己的密钥库文件.//参见 https://facebook.github.io/react-native/docs/signed-apk-android.签名配置signingConfigs.debugminifyEnabled enableProguardInReleaseBuildsproguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro";}}//applicationVariants 是例如调试,发布applicationVariants.all { 变体 ->variant.outputs.each { 输出 ->//对于每个架构的每个单独的 APK,设置一个唯一的版本代码,如下所述://https://developer.android.com/studio/build/configure-apk-splits.htmldef versionCodes = [armeabi-v7a":1,x86":2,arm64-v8a":3,x86_64":4]def abi = output.getFilter(OutputFile.ABI)if (abi != null) {//通用调试、通用发布变体为空output.versionCodeOverride =versionCodes.get(abi) * 123456 + defaultConfig.versionCode}}}

所以我是这样添加的:

buildTypes {调试{签名配置signingConfigs.debug}释放 {//注意!在生产中,您需要生成自己的密钥库文件.//参见 https://facebook.github.io/react-native/docs/signed-apk-android.签名配置signingConfigs.debugminifyEnabled enableProguardInReleaseBuildsproguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro";}}产品风味{开发{resValue "string", "app_name", getAppName("INT")resValue "string", "link_launcher", getLauncher("dv")applicationIdSuffix .dv"manifestPlaceholders = [onesignal_app_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: "",onesignal_google_project_number:123456789"]}u {resValue "string", "app_name", getAppName("UA")resValue "string", "link_launcher", getLauncher("ua")applicationIdSuffix .ua"manifestPlaceholders = [onesignal_app_id: "",onesignal_google_project_number:123456789"]}产品{resValue "string", "app_name", getAppName()resValue "string", "link_launcher", getLauncher()manifestPlaceholders = [onesignal_app_id: "",onesignal_google_project_number:601125149914"]}}//applicationVariants 是例如调试,发布applicationVariants.all { 变体 ->variant.outputs.each { 输出 ->//对于每个架构的每个单独的 APK,设置一个唯一的版本代码,如下所述://https://developer.android.com/studio/build/configure-apk-splits.htmldef versionCodes = [armeabi-v7a":1,x86":2,arm64-v8a":3,x86_64":4]def abi = output.getFilter(OutputFile.ABI)if (abi != null) {//通用调试、通用发布变体为空output.versionCodeOverride =versionCodes.get(abi) * 1048576 + defaultConfig.versionCode}}}

buildTypes 看起来与原始遗留的 buildTypes 有点不同,所以我不确定这是否可以,但无论如何我然后运行了 npm run再次在本地构建并出现此错误:

* 其中:构建文件/Users/danale/Projects/NFIBEngage/android/app/build.gradle"行:168* 什么地方出了错:评估项目:app"时出现问题.>在 ProductFlavor_Decorated{name=dev, dimension=null, minSdkVersion=null, targetSdkVersion=null, renderscriptTargetApi=null, renderscriptSupportModeEnabled=null, renderscriptSupportModeBlasEnabled=null, renderscriptNdkModeEnabled=null, versionCode=null 上找不到参数 [INT] 的 getAppName() 方法, versionName=null, applicationId=null, testApplicationId=null, testInstrumentationRunner=null, testInstrumentationRunnerArguments={}, testHandleProfiling=null, testFunctionalTest=null,signingConfig=null, resConfig=null, mBuildConfigFields={}, mResValues={}, mProguardFiles=[], mConsumerProguardFiles=[], mManifestPlaceholders={}, mWearAppUnbundled=null} 类型为 com.android.build.gradle.internal.dsl.ProductFlavor.

我能够通过添加缺少的方法来解决本地错误,如下所示:

def appName = "Engage";/*** 从命令行参数中获取版本名称** @return int 如果参数 -PversionName 存在,则返回 int 值或 -1*/def getAppName = { env ->return (env ? appName + "("+ env + ")" : appName);}/*** 从命令行参数获取版本名称** @return int 如果参数 -PversionName 存在,则返回 int 值或 -1*/def getLauncher = { env ->return (env ? engage-" + env + .nfib.org" : engage.nfib.org");}安卓 {compileSdkVersion rootProject.ext.compileSdkVersion编译选项{sourceCompatibility JavaVersion.VERSION_1_8targetCompatibility JavaVersion.VERSION_1_8}风味维度默认"默认配置{applicationIdcom.nfib.engage"minSdkVersion rootProject.ext.minSdkVersiontargetSdkVersion rootProject.ext.targetSdkVersion版本代码 1版本名称1.0"}分裂{阿比{重启()启用 enableSeparateBuildPerCPUArchitectureUniversalApk false//如果为 true,也生成一个通用 APK包括armeabi-v7a"、x86"、arm64-v8a"、x86_64"}}签名配置{调试{storeFile 文件('debug.keystore')storePassword 'android'keyAlias 'androiddebugkey'keyPassword 'android'}}构建类型{调试{签名配置signingConfigs.debug}释放 {//注意!在生产中,您需要生成自己的密钥库文件.//参见 https://facebook.github.io/react-native/docs/signed-apk-android.签名配置signingConfigs.debugminifyEnabled enableProguardInReleaseBuildsproguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro";}}产品风味{开发{维度默认"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{维度默认"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"]}u {维度默认"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"]}产品{维度默认"resValue "string", "app_name", getAppName()resValue "string", "link_launcher", getLauncher()manifestPlaceholders = [onesignal_app_id:82dcb42f-1d35-4b79-bc28-2d1d02dbda36",onesignal_google_project_number:601125149914"]}}

不幸的是,我继续在 Jenkins 中遇到同样的错误.

解决方案

一些使构建工作的更改,来自评论:

从您的 package.json 中,您的 cli 版本在 ^2.0.12.0.1 确实是具有您链接到的问题的 cli 版本来自 github.com/facebook/react-native/issues/25479 您是否验证过类似于 def command = "../node_modules/.bin/react-native config" 的行(来自 github.com/facebook/react-native/issues/...) 在您的 node_modules/@react-native-community/cli-platform-android/native_modules.gradle 中是否正确?您还应该确保您安装的 cli 版本是 >= 2.0.2.

确保您在 android/app/build.gradle 中的 buildTypesproductFlavors 定义设置为包括您所使用的所有不同变体试图建立你的詹金斯工作.看起来你有 devqauaprod 的风格.查看 gradle 文档 developer.android.com/studio/build/build-variants#build-types 了解更多信息.

看起来您的 build.gradle 中缺少 getAppName 函数.类似于 ext.getAppName = {suffix = '' ->'MyAppName' + 后缀}.快速扫描您的 build.gradle 看起来您需要另一个名为 getLauncher 的文件,它会为您使用 link_launcher 的任何内容返回适当的字符串.>

My Jenkins build has given me the following error:

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 

It seems the problem is with the @react-native-community/cli-platform node module, but reading over this closed issue: https://github.com/facebook/react-native/issues/25479

its unclear to me what exactly is the proposed and final solution to this.

There is a recommendation on a fix that is more straightforward in this react-native issue: https://github.com/facebook/react-native/issues/25822

but my error is not complaining about that line.

As far as installing @react-native-community/cli I believe I already have it inside my package-lock.json file:

"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",

Others mentioned something about app/build.gradle, here is the relevant part of mine:

// 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)

Mention was also made of android/settings.gradle, this one is mine:

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'

From what I have gathered here:

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

The above files are correct.

So what exactly is wrong here and how do I fix it?

In terms of node_modules/@react-native-community/cli-platform-android/native_modules.gradle line 190 is this one:

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

Could the problem be with how I wrote index.js file:

/**
 * @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://asdf@sentry.io/123456677"
).install();

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

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

Is AppRegistry.registerComponent() written correctly?

I ran the Jenkins script locally, which I believe is this script right here:

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 and locally I got this error:

FAILURE: Build failed with an exception.

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

Are these related errors? Anyone experienced with React Native builds?

As suggested, I looked into my android/app/build.gradle file for productFlavors and noticed that indeed they were missing between here:

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
            }

        }
    }

So I added it like so:

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
            }

        }
    }

The buildTypes is looking a bit different than the original legacy buildTypes so I am not sure if that's okay, but at any rate I then ran npm run build again locally and got this error:

* 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.

I was able to resolve the local error by adding the missing methods like so:

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"]
      }
    }

Unfortunately, I continue to get the same error in Jenkins.

解决方案

Some of the changes to get the build working, from comments:

From your package.json, your cli version is at ^2.0.1 and 2.0.1 is indeed the version of the cli that had the issue you linked to from github.com/facebook/react-native/issues/25479 Have you verified that the line similar to def command = "../node_modules/.bin/react-native config" (from github.com/facebook/react-native/issues/…) in your node_modules/@react-native-community/cli-platform-android/native_modules.gradle is correct? You should also ensure your installed version of the cli is >= 2.0.2.

Make sure your buildTypes and productFlavors definitions in android/app/build.gradle are set up to include all the different variants you are trying to build in your jenkins job. Looks like you have flavors for dev, qa, ua and prod. Check out the gradle docs developer.android.com/studio/build/build-variants#build-types for more info.

Looks like you're missing a getAppName function in your build.gradle. Something like ext.getAppName = {suffix = '' -> 'MyAppName' + suffix}. A quick scan of your build.gradle looks like you need another called getLauncher which returns an appropriate string for whatever you use link_launcher for.

这篇关于React Native 构建错误:文本不得为 null 或为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆