Himanshu
Himanshu

Reputation: 181

Resolve a module conditionally in react-native

I want to import ReactNativePropRegistry in my React Native package.

I used to import it from 'react/lib/ReactNativePropRegistry' before React Native 0.38.0 but it has changed to 'react-native/Libraries/Renderer/src/renderers/native/ReactNativePropRegistry' in React Native 0.38.0.

I want my package to be supported on all the React Native versions including 0.38.0 so I did this

if(semver.gte(reactNativeVersion, '0.38.0-rc.0')) {
  const ReactNativePropRegistry = require('react-native/Libraries/Renderer/src/renderers/native/ReactNativePropRegistry');
} else {
  const ReactNativePropRegistry = require('react/lib/ReactNativePropRegistry');
}

But it seems that the packager tries to resolve the modules statically. So even if reactNativeVersion is less than 0.38.0-rc.0, it tries to resolve the module at this path 'react-native/Libraries/Renderer/src/renderers/native/ReactNativePropRegistry' which causes it to throw an error Unable to resolve module ....

Is there any way get around this?

Upvotes: 4

Views: 1256

Answers (1)

jevakallio
jevakallio

Reputation: 35920

You cannot do dynamic imports. However, because the React Native packager uses node-haste and both React and React Native use the Haste @providesModule declarations, you may be able to import the module by name without specifying the location:

require('ReactNativePropRegistry');

I haven't tried it for this particular module, but in theory it should work.

It might be good to know that some distant future version of the RN, the packager may drop support for requiring modules by the providesModule name across package boundaries, so this may not be a permanent solution.

However if you're working on a library, eventually you can just deprecate support for versions older than 0.38. Or could you do that already?

Upvotes: 1

Related Questions