A clean approach to load your node packages in React Native Webview

Creating an app with strong offline-first support is always a challenge. All resources need to be downloaded beforehand and some of these resources could be your custom html/js files that you would like to be accessible to users when they are offline.
In this article, we will talk about how to load such resources in react-native-webview.
Note, only use react-native-webview when you truly need it or when you want to a keep consistent user experience across web and mobile platforms with little effort.

Here is a high-level summary of the steps we need-

  • Get JS files into app assets
  • Copy JS files to file directory
  • Load JS files into webview via static server

With that, let’s start-
To get the required JS files to app assets, add a postinstall script to copy js files to asset folder. If you have many files, create a gulp task to make it more elegant.

Notice the files are copied with .webview file extension instead of .js, this is because .js extension is already present in the sourceExt of metro bundler, so it doesn’t support keeping JS files into the assets folder (See: https://github.com/expo/expo-cli/issues/2077#issuecomment-625535276). To overcome it we add a new webview ext to assetExt in metro.config.js.

Next, we need to load these files in a webview via a static server. One convenient way to do it is to copy these JS files from the asset directory to the file directory. With that, it will be much easier to load them.

With everything in place, add a service to manage a static server created with react-native-static-server

Now, use relative paths to seamlessly load the offline content in react-native-webview. You can inject the JS paths via injectJavascript prop or use Html prop to pass Html string with correct paths.

Hope this helped you out.
Thanks.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store