Search code examples
androidbundlereact-nativeassets

Bundled image in React Native not found on Android


I'm building a React Native App for both ios and android. Assets (images, sounds, etc.) are all stored locally and preloaded during App's launch by a manager for later use.

Everything works fine on ios in debug & release modes and on android in debug mode but images won't display on android in release mode, even after bundling them.

First assets are preloaded from the Asset Manager in src/assets/index.js

import { Image } from 'react-native'

const assets = {
    images: {
        'icon.png': require('./images/icon.png')
    }
}

const preloadedAssets = {}

const getImage = (name, extension = 'png') => {
    return getAsset('images', `${name}.${extension}`)
}

const getAsset = (type, name) => {
    return preloadedAssets[type][name]
}

const preloadImages = () => {
    preloadedAssets.images = {}

    return Promise.all(
        Object.keys(assets.images).map(name => {
            const source = Image.resolveAssetSource(assets.images[name])

            return Image
                .prefetch(source.uri)
                .then(() => {
                    preloadedAssets.images[name] = {
                        source: assets.images[name],
                        ...source
                    }
                })
        })
    )
}

const preload = () => {
    return preloadImages()
}

export default {
    preload,
    getImage
}

Then images are rendered as follow

import AssetManager from '../assets'
const asset = AssetManager.getImage('icon.png')
<Image source={asset.source} style={{ width: ..., height: ... }} />

I bundled with the following command

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/

I also tried to copy all assets to android/app/src/main/assets/ folder and replace require('./images/icon.png') with { uri: 'file:///android_asset/images/icon.png' } but images are still not displayed.

Project structure

project


Solution

  • I ended up building a react-native project from scratch on version 0.59.4 (previously 0.57.1).

    Now everything's working fine, apks can be generated without bundling with following commands :

    cd android && ENVFILE=../.env.production ./gradlew assembleProdRelease && cd ..
    cd android && ENVFILE=../.env.development ./gradlew assembleDevRelease && cd ..
    

    I also removed Image.prefetch as it won't work on android release.