question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

after upgrade 0.67.3 -> 0.70.4 build release apk was success but miss index.android.bundle when start app with Flavors

See original GitHub issue

New Version

0.70.4

Old Version

0.67.3

Build Target(s)

android real machine in release flavor

Output of react-native info

System: OS: macOS 10.15.4 CPU: (8) x64 Intel® Core™ i5-8259U CPU @ 2.30GHz Memory: 527.52 MB / 16.00 GB Shell: 3.2.57 - /bin/bash Binaries: Node: 16.14.0 - /usr/local/bin/node Yarn: 1.22.4 - /usr/local/bin/yarn npm: 8.3.1 - /usr/local/bin/npm Watchman: 4.9.0 - /usr/local/bin/watchman Managers: CocoaPods: 1.11.2 - /Users/zaffy/.rbenv/shims/pod SDKs: iOS SDK: Platforms: iOS 14.4, DriverKit 20.2, macOS 11.1, tvOS 14.3, watchOS 7.2 Android SDK: Android NDK: 21.0.6113669 IDEs: Android Studio: 4.2 AI-202.7660.26.42.7486908 Xcode: 12.4/12D4e - /usr/bin/xcodebuild Languages: Java: 11.0.15.1 - /Library/Java/JavaVirtualMachines/jdk-11.0.15.1.jdk/Contents/Home//bin/javac npmPackages: @react-native-community/cli: Not Found react: 18.0.0 => 18.1.0 react-native: 0.70.4 => 0.70.4 react-native-macos: Not Found npmGlobalPackages: react-native: Not Found

Issue and Reproduction Steps

I follow the steps on this page https://react-native-community.github.io/upgrade-helper/?from=0.67.3&to=0.70.4, assemble flavor release apk success, but crash when start app, logcat print Unable to load script. Make sure you're either running Metro (run 'npx react-native start') or that your bundle 'index.android.bundle

but log tell me copy bundle success:

info Writing bundle output to:,/Users/zaffy/work/app.shihuimiao/android/app/build/generated/assets/react/kjk/release/index.android.bundle
info Writing sourcemap output to:, /Users/zaffy/work/app.shihuimiao/android/app/build/intermediates/sourcemaps/react/kjk/release/index.android.bundle.packager.map
info Done writing bundle output
info Done writing sourcemap output
info Copying 502 asset files
info Done copying assets

The following are important file contents:

app/build.gradle

apply plugin: "com.android.application"

import com.android.build.OutputFile

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * ........
 */

project.ext.react = [
    entryFile   : "index.js",
    enableHermes: true
]
apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"

apply plugin: 'kotlin-android'
apply plugin: 'AsmPlugin'
apply plugin: 'android-junk-code'
// apply huawei agconnect only for kjk
if (getGradle().getStartParameter().getTaskRequests().toString().contains("Kjk")) {
    apply plugin: 'com.huawei.agconnect'
}

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = true

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = true

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US.  Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Whether to enable the Hermes VM.
 *
 * This should be set on project.ext.react and that value will be read here. If it is not set
 * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
 * and the benefits of using Hermes will therefore be sharply reduced.
 */
def enableHermes = project.ext.react.get("enableHermes", false)

/**
 * Architectures to build native code for in debug.
 */
def nativeArchitectures = project.getProperties().get("reactNativeDebugArchitectures")

/**
 * Architectures to build native code for.
 */
def reactNativeArchitectures() {
    def value = project.getProperties().get("reactNativeArchitectures")
    return value ? value.split(",") : ["armeabi-v7a", "arm64-v8a"]
}

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion
    signingConfigs {
        kjk {
            keyAlias 'xxxxxxx'
            keyPassword 'xxxxxxx'
            storeFile file('../keystores/kjk.keystore')
            storePassword 'bz7W8qYkRpns'
        }

        mkl {
            keyAlias 'xxxxxxx'
            keyPassword 'xxxxxxx'
            storeFile file('../keystores/mkl.keystore')
            storePassword 'xxxxxxx'
        }
    }


    defaultConfig {
        applicationId "xxxxxxxxx"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 191400
        versionName "19.14.0"
        resConfigs "zh"
        useLibrary 'org.apache.http.legacy'
        buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
        if (isNewArchitectureEnabled()) {
            // We configure the NDK build only if you decide to opt-in for the New Architecture.
            externalNativeBuild {
                ndkBuild {
                    arguments "APP_PLATFORM=android-21",
                        "APP_STL=c++_shared",
                        "NDK_TOOLCHAIN_VERSION=clang",
                        "GENERATED_SRC_DIR=$buildDir/generated/source",
                        "PROJECT_BUILD_DIR=$buildDir",
                        "REACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid",
                        "REACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build",
                        "NODE_MODULES_DIR=$rootDir/../node_modules"
                    cFlags "-Wall", "-Werror", "-fexceptions", "-frtti", "-DWITH_INSPECTOR=1"
                    cppFlags "-std=c++17"
                    // Make sure this target name is the same you specify inside the
                    // src/main/jni/Android.mk file for the `LOCAL_MODULE` variable.
                    targets "rndiffapp_appmodules"
                }
            }
            if (!enableSeparateBuildPerCPUArchitecture) {
                ndk {
                    abiFilters (*reactNativeArchitectures())
                }
            }
        }

        // workaround of code push with AGP4.1+ issue
        // check out https://github.com/microsoft/react-native-code-push/issues/1961 for status update
        resValue 'string', "CODE_PUSH_APK_BUILD_TIME", String.format("\"%d\"", System.currentTimeMillis())

        // for react-native-config to work with build variants
        resValue "string", "build_config_package", "xxxxxxx"
    }
    if (isNewArchitectureEnabled()) {
        // We configure the NDK build only if you decide to opt-in for the New Architecture.
        externalNativeBuild {
            ndkBuild {
                path "$projectDir/src/main/jni/Android.mk"
            }
        }
        def reactAndroidProjectDir = project(':ReactAndroid').projectDir
        def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        afterEvaluate {
            // If you wish to add a custom TurboModule or component locally,
            // you should uncomment this line.
            // preBuild.dependsOn("generateCodegenArtifactsFromSchema")
            preDebugBuild.dependsOn(packageReactNdkDebugLibs)
            preReleaseBuild.dependsOn(packageReactNdkReleaseLibs)

            // Due to a bug inside AGP, we have to explicitly set a dependency
            // between configureNdkBuild* tasks and the preBuild tasks.
            // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732
            configureNdkBuildRelease.dependsOn(preReleaseBuild)
            configureNdkBuildDebug.dependsOn(preDebugBuild)
            reactNativeArchitectures().each { architecture ->
                tasks.findByName("configureNdkBuildDebug[${architecture}]")?.configure {
                    dependsOn("preDebugBuild")
                }
                tasks.findByName("configureNdkBuildRelease[${architecture}]")?.configure {
                    dependsOn("preReleaseBuild")
                }
            }
        }
    }
    splits {
        abi {
            enable enableSeparateBuildPerCPUArchitecture
            reset()
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a","arm64-v8a"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            shrinkResources enableProguardInReleaseBuilds
            zipAlignEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro"
        }

        debug {
            signingConfig release.signingConfig
        }
    }

    flavorDimensions "default"
    productFlavors {
        kjk {
            dimension "default"
            signingConfig signingConfigs.kjk
        }

        mkl {
            dimension "default"
            applicationId "xxxxxxxxx"
            signingConfig signingConfigs.mkl
        }

    }


    // 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:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
            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 =
                    defaultConfig.versionCode * 1000// + versionCodes.get(abi)
            }
        }
    }

    packagingOptions {
        // react-native
        //pickFirst '**/armeabi-v7a/libc++_shared.so'
        //pickFirst '**/arm64-v8a/libc++_shared.so'
        //pickFirst '**/x86/libc++_shared.so'
        //pickFirst '**/x86_64/libc++_shared.so'
        // 不压缩so包
        doNotStrip "*/armeabi-v7a/*.so"
        doNotStrip "*/arm64-v8a/*.so"
        doNotStrip "*/x86/*.so"
        doNotStrip "*/x86_64/*.so"
        doNotStrip "armeabi.so"
    }

    sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }
}

dependencies {
    def kotlin_version = rootProject.ext.kotlinVersion
    configurations.all {
        resolutionStrategy.force 'androidx.appcompat:appcompat:1.3.0'
        resolutionStrategy.force "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    }

    implementation fileTree(include: ['*.jar'], dir: 'libs')
    // react native
    implementation 'com.facebook.react:react-native:+'
    // For animated GIF support
    implementation 'com.facebook.fresco:animated-gif:2.6.0'
    // For WebP support, including animated WebP
    implementation 'com.facebook.fresco:animated-webp:2.6.0'
    implementation 'com.facebook.fresco:webpsupport:2.6.0'

    //ad SDK
    implementation files('libs/android-gif-drawable-1.2.6.aar')

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

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

    // react native code push needs manual link
    implementation project(':react-native-code-push')

    ....
}

if (isNewArchitectureEnabled()) {
    // If new architecture is enabled, we let you build RN from source
    // Otherwise we fallback to a prebuilt .aar bundled in the NPM package.
    // This will be applied to all the imported transtitive dependency.
    configurations.all {
        resolutionStrategy.dependencySubstitution {
            substitute(module("com.facebook.react:react-native"))
                .using(project(":ReactAndroid"))
                .because("On New Architecture we're building React Native from source")
            substitute(module("com.facebook.react:hermes-engine"))
                .using(project(":ReactAndroid:hermes-engine"))
                .because("On New Architecture we're building Hermes from source")
        }
    }
}

// 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.implementation
    into 'libs'
}

def isNewArchitectureEnabled() {
    // To opt-in for the New Architecture, you can either:
    // - Set `newArchEnabled` to true inside the `gradle.properties` file
    // - Invoke gradle with `-newArchEnabled=true`
    // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
    return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}

// Compile typescript and make bundleJS depends on it
task buildTypeScript(type: Exec) {
    group = "react"
    description = "typescript compile"
    commandLine('npm', 'run', 'build')
}

afterEvaluate {
    def isAndroidLibrary = plugins.hasPlugin("com.android.library")
    def variants = isAndroidLibrary ? android.libraryVariants : android.applicationVariants
    variants.all { def variant ->
        // make react bundle js depends on the compile typescript for release build
        def buildType = variant.buildType.name
        if (buildType == "release") {
            def targetName = variant.name.capitalize()
            def bundleJSTask = tasks.findByName("bundle${targetName}JsAndAssets")
            bundleJSTask.dependsOn(buildTypeScript)
        }
    }
}

android/build.gradle

classpath 'com.android.tools.build:gradle:7.1.1'
classpath("com.facebook.react:react-native-gradle-plugin")
classpath("de.undercouch:gradle-download-task:5.0.1")
...
ext {
    buildToolsVersion = '31.0.0'
    minSdkVersion = 21
    compileSdkVersion = 31
    targetSdkVersion = 29
    kotlinVersion = "$kotlin_version"
    qukanPlayerVersion= '4.1.0529.1159'
    if (System.properties['os.arch'] == "aarch64") {
        // For M1 Users we need to use the NDK 24 which added support for aarch64
        ndkVersion = "24.0.8215888"
    } else {
        // Otherwise we default to the side-by-side NDK version from AGP.
        ndkVersion = "21.4.7075529"
    }
    gsonVersion='2.8.8'
    constraintlayoutVersion='2.1.3'
}

gradle.properties

FLIPPER_VERSION=0.125.0
android.injected.testOnly=false
# use AndroidX with legacy dependencies need jetify
android.enableJetifier=true
android.useAndroidX=true
# disable AGP 4.2 reesource optimization so that baichuan can find its safe image resource
# https://jakewharton.com/smaller-apks-with-resource-optimization/
android.enableResourceOptimizations=false
# jvm needs memory more than default
org.gradle.jvmargs=-Xmx4096M -XX:MaxMetaspaceSize=512m -Dkotlin.daemon.jvm.options\="-Xmx4096M"
# Use this property to specify which architecture you want to build.
# You can also override it from the CLI using
# ./gradlew <task> -PreactNativeArchitectures=x86_64
reactNativeArchitectures=armeabi-v7a,arm64-v8a
# Use this property to enable support to the new architecture.
# This will allow you to use TurboModules and the Fabric render in
# your application. You should enable this flag either if you want
# to write custom TurboModules/Fabric components OR use libraries that
# are providing them.
newArchEnabled=false

gradle-wrapper.properties

....
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-all.zip

package.json

{
  "name": "xxxxxxx",
  "version": "20.14.0",
  "private": true,
  "scripts": {
    "msf": "if [ ! -d ./dist ]; then mkdir -p ./dist; fi && msf ./src ./dist --mode update",
    "tsc": "tsc --skipLibCheck",
    "copy-assets": "copyfiles './src/**/*.{webp,jpg,jpge,png,gif,json}' ./dist/ -u 1",
    "start": "./scripts/start.sh",
    "build": "npm run tsc && npm run copy-assets",
    "clean": "scripts/clean.sh",
    "eslint": "eslint --cache --cache-strategy content src/",
    "lint": "npm run tsc -- --noEmit && npm run eslint",
    "my-eslint-issues": "npm run eslint | docker-run --no-args-path-mapping shm-run parse-lint-output --project-root $PWD --user",
    "update": "npm run clean && npm ci && npm run update-ios",
    "update-ios": "cd ios && pod install && cd ..",
  ......
    "test": "jest --forceExit",
    "postinstall": "patch-package"
  },
  "dependencies": {
    "@react-native-async-storage/async-storage": "1.16.1",
    "@react-native-clipboard/clipboard": "1.9.0",
    "@react-native-community/cameraroll": "4.1.2",
    "@react-native-community/masked-view": "0.1.11",
    "@react-native-community/netinfo": "8.0.0",
    "@react-native-community/slider": "4.2.0",
    "@react-navigation/bottom-tabs": "6.3.1",
    "@react-navigation/native": "6.0.10",
    "@react-navigation/stack": "6.2.1",
    "@sentry/core": "6.19.7",
    "@sentry/react-native": "3.2.13",
    "@sentry/types": "6.19.7",
....
    "deprecated-react-native-prop-types": "^2.3.0",
    "create-fetcher": "0.6.2",
    "dayjs": "1.11.3",
    "hoist-non-react-statics": "3.3.2",
    "lodash-es": "4.17.21",
    "lottie-ios": "3.2.3",
    "lottie-react-native": "5.0.1",
    "object-hash": "3.0.0",
    "react": "18.1.0",
    "react-native": "0.70.4",
    "react-native-code-push": "7.0.4",
    "react-native-config": "1.4.5",
    "react-native-device-info": "8.4.9",
    "react-native-fs": "2.19.0",
    "react-native-gesture-handler": "2.2.0",
    "react-native-get-random-values": "1.7.2",
    "react-native-linear-gradient": "2.5.6",
    "react-native-pager-view": "5.4.15",
    "react-native-permissions": "3.2.0",
    "react-native-reanimated": "2.9.1",
    "react-native-safe-area-context": "3.4.1",
    "react-native-screens": "3.12.0",
    "react-native-snap-carousel": "3.9.1",
    "react-native-svg": "12.1.1",
    "react-native-tab-view": "3.1.1",
    "react-native-webview": "11.17.2",
    "react-native-webview-comlink": "0.7.6",
    "redux": "4.2.0",
    "redux-actions": "2.6.5",
    "reselect": "4.1.6",
    "uuid": "8.3.2"
  },
  "devDependencies": {
    "@types/hoist-non-react-statics": "3.3.1",
    "@types/lodash-es": "4.17.6",
    "@types/object-hash": "2.2.1",
    "@types/react-native": "0.70.4",
    "@types/react-native-snap-carousel": "3.8.5",
    "@types/redux-actions": "2.6.2",
    "@types/uuid": "8.3.4",
    "concurrently": "7.2.2",
    "copyfiles": "2.4.1",
    "jest": "28.1.1",
    "jetifier": "2.0.0",
    "metro-react-native-babel-preset": "0.72.3",
    "msf-cli": "1.2.5",
    "patch-package": "6.4.7",
    "typescript": "4.7.4"
  }
}

Issue Analytics

  • State:open
  • Created a year ago
  • Reactions:8
  • Comments:15 (5 by maintainers)

github_iconTop GitHub Comments

3reactions
cortinicocommented, Oct 28, 2022

Just a heads up that I fixed this and it’s going to be released in RN 0.71

2reactions
cortinicocommented, Nov 25, 2022

@zaffy88 Actually, if you don’t want to wait for the fix in 0.71, you can try this temporary workaround in package.json instead of generating bundle manually, it helped me:

I would highly advice against doing this kind of fixes as 1. It will most likely won’t work 2. If you forget you added this script in your package.json, your upgrade in the future will be really painful.

Read more comments on GitHub >

github_iconTop Results From Across the Web

index.android.bundle missing in APK after upgrading to RN 0.68
Found it after comparing the build files with a brand new RN app! I had classpath("com.android.tools.build:gradle:7.1.2"). in android/build.
Read more >
Fixing React-Native android release build - wesionaryTEAM
Android release build crashes on launch but works fine in development mode. After months of research and development, your app is finally ready...
Read more >
Bundling React Native during Android release builds
Older versions of React Native's docs (0.19) recommended running the bundling command manually before building your app if you don't have a react.gradle...
Read more >
Android release build still attempting to connect to metro - Reddit
It was a comedy of errors, a dependency on notifee required the target and compile SDK versions to be 33, which in turn...
Read more >
Handling 64-bit Android Builds for React Native - Red Shift
This post assumes you've already upgraded React Native in your app to ≥ 0.59.8 ... key Build > Generate Signed Bundle/APK, which should...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found