1

I have an npm library that is made to work in a browser and in a Node environment.

When used in a node environment it checks if the require function exists, and requires modules such as fs.

var fs = null;
if (typeof require !== 'undefined') {
  fs = require('fs');
}

Such modules do not exist in react native and therefore when I use this library in react native, I get an error.

What's the best way to know if we're in a react native context vs node ?

Julien Fouilhé
  • 2,583
  • 3
  • 30
  • 56

2 Answers2

0

AFAIK, there is no way to do this without you setting it somewhere explicitly. React native does have require but not fs. this is probably why you get the error. global is also available on both, so it might be an option to store an isReact variable in the global Object.

global.isReact = true. isReact will be available throughout your app. Many say it is not wise to use global variables but in this case it can be an exception.

You also create an env.js file in your root dir where you set a isReact variable and require that file whenever you need to determine whether you're running in React Native or Node.

borislemke
  • 8,446
  • 5
  • 41
  • 54
0

Unfortunately, @borislemke's answer did not work, it appears that you cannot conditionalize require. I think it's babel that constructs the tree of dependencies without taking into account the conditions.

I finally moved the require into a file that gets added with grunt

Julien Fouilhé
  • 2,583
  • 3
  • 30
  • 56