How to Lazy-Load a React Native module from a path stored in a variable

1.1k Views Asked by At

I've been trying to load a React Native component dynamically, but to no success. It seems like React Native doesn't like it at all when you try passing it a module path stored in a variable :

This works very well - React.lazy :

const OtherComponent = React.lazy(() => import('./path/to/my/module'));

This also works like a charm Full dynamic import : - Full dynamic import : @loadable/component

(npm @loadable/component)

import loadable from '@loadable/component'
const AsyncPage = loadable(props => import('./path/to/my/module'))

but try changing any to this :

var myModulePath = './path/to/my/module';  

const AsyncPage = loadable(props => import(myModulePath))

or this :

const OtherComponent = React.lazy(() => import(myModulePath));

and all goes crazy!

How can I go about loading a module dynamically, say at runtime, or just have the path briefly held in a variable, instead of passing it as a string literal

From the documentation (Full dynamic import : @loadable/component),

import loadable from '@loadable/component'
const AsyncPage = loadable(props => import(`./${props.page}`))

a dynamically generated path should work, but my React Native attempts don't.

Are there any ideas out there?

Thank you all in advance.

1

There are 1 best solutions below

0
On

You can do it using https://github.com/microsoft/react-native-code-push

About lazy loading, it is not needed if you use the Hermes JS engine. Otherwise, you can use RAM bundler: https://reactnative.dev/docs/ram-bundles-inline-requires