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:
How in general you would recommend to make my library to work in both Node and ReactNative?
Thanks,
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With