Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading modules conditionally in react-native

Tags:

react-native

I'm working to make a library to work on both NodeJS and ReactNative. Some of the native NodeJS modules are not supported in ReactNative, so I tried to load them conditionally. This however doesn't work:

if (true) {
    require('a'); // module 'a' works in ReactNative
} else {
    require('b'); // module 'b' doesn't work in ReactNative
}

Unfortunately, BOTH require statements ad executed and loading of 'b' throws exception :(

Now I have the following options:

  1. To create a new version of the library, specific for ReactNative, using only modules, which work there.
  2. I've heard you can specify "react-native" in package.json and this would help to resolve this issue. However, I can't find documentation anywhere, is it documented somewhere?

How in general you would recommend to make my library to work in both Node and ReactNative?

Thanks,

like image 615
Joachim Avatar asked Mar 27 '17 20:03

Joachim


2 Answers

I figured it out - this is done using the "react-native" property in package.json. There you can either replace a module with another one, or to disable it for ReactNative (by setting its value to false). If you replace the module with another one, this module should be added to the list of dependencies too.

In the example above, for module b in react-native property you have to set false as value.

In package.json this might look like this:

"dependencies": {
  "c": "^1.0.0"
},
"react-native": {
  "a": "c",
  "b": false
}

The code above will replace module a with module c in case of ReactNative and it will suppress the loading of module b (it will look like an empty object).

like image 68
Joachim Avatar answered Oct 22 '22 04:10

Joachim


You can try below code :

if (true)
{
    /* this module will get bundled in react-native app */
    require('a'); // module 'a' works in ReactNative
} else {
    let b = 'b'
    /* this module will not get bundled in react-native app */
    require(b); // module 'b' doesn't work in ReactNative
}
  • require('a')

    is included in the bundle by packager before executing the js bundle .It doesnt require at the runtime. react-native maintains a map of all the required modules and it generally replaces module name with id.

  • let b = 'b'

    require(b)

    is like a dynamic require which is not bundled by packager and is requested at runtime. It then searches this module in its map, as this map will not have this module, so react-native will throw error.

Note: In your case

if(true)

is a condition which will never execute the else part of if if-else, so react-native will never throw error like module not found.

like image 1
Ayush Nawani Avatar answered Oct 22 '22 02:10

Ayush Nawani