react-native webView android using local html issue

When react-native WebView components use local html, they are generally used in this way

var source =  require('../html/my.html') : 
<WebView  source={source} />

In debug mode, there is no problem with android and ios.
However, in release mode, that is, when packaging, Android will not be able to read the html path, resulting in failure to load successfully!

After searching for some information on the Internet, I learned that the html should be placed under the android resource directory, and the file:///android_asset/ path can be used to load it!
Specific path: android/app/src/main/assets
We create an html folder under this path, and specifically place our html
code to modify it

// 区分ios和android
var source = (Platform.OS == 'ios') ? require('../html/my.html') : {uri: "file:///android_asset/html/my.html"}

Hmm~~ Then every time we modify the html code, we have to copy the code twice, which is a bit unacceptable
. Modify it. After modifying the html code, it will be automatically copied to the android resource directory every time you compile it.
Open android/app/build.gradle
to add

// Android currently requires the HTML files in React Native to be
// in the Android Assets
// https://github.com/facebook/react-native/pull/17304
task copyReactNativeHTML(type: Copy) {
    from '../../app/html'
    into 'src/main/assets/html'
}
// Note that you may need to add other build variants
gradle.projectsEvaluated {
    bundleDebugJsAndAssets.dependsOn(copyReactNativeHTML)
    bundleReleaseJsAndAssets.dependsOn(copyReactNativeHTML)
}

ok, so you don't have to manually copy it every time you compile android

Wait~
We know that the debug mode is no problem, so in order to be compatible with the debug mode, there is no need to manually copy and modify it again, and the final result is as follows

var source = ""
if (__DEV__) {
      // debug模式
      source = require('../html/my.html')
} else {
      // release模式
      source = (Platform.OS == 'ios') ? require('../html/my.html') : {
        uri: "file:///android_asset/html/my.html"
      }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324690825&siteId=291194637