Search code examples
androidreact-nativegoogle-play-servicesreact-native-maps

How to get React Native to require/import function from package only on Android OS


How can I import a function only for a specific platform?

When using react-native-maps I want to import PROVIDER_GOOGLE from react-native-maps only for Android app users, so that I don't overuse the Google Service API (and take advantage of Apple Map's lack of metering). e.g. I only want PROVIDER_GOOGLE imported if the app is running on Android.

import MapView, { Marker, PROVIDER_GOOGLE } from "react-native-maps";

What does React-Native Documentation suggest?

React native platform-specific-code documentation suggests ways of importing components, but doesn't show a pattern to require PROVIDER_GOOGLE from react-native-maps. I want react-native-maps itself to be imported for both OS's.

const Component = Platform.select({
  ios: () => require('ComponentIOS'),
  android: () => require('ComponentAndroid')
})();

<Component />

The other pattern suggested is to have an OS specific file e.g.

MyMap.ios.js
MyMap.android.js

So I can then require the component as follows:

import MyMap from './MyMap';

This way I could only have the PROVIDER_GOOGLE import in the MyMap.android.js flavor.

While this solution works, I'm having to copy/paste literally every thing else, which seems quite inefficient, so was looking for a better method to require the function itself only for a specific platform.


Solution

  • Let the function exist then require the package and get the function

    let functionNeeded; if (true) { functionNeeded = require( package ).functionNeeded; }
    

    This may be obvious to seasoned users of "require", but wasn't to me based on the RN documentation or even similar questions and answers SO 1 2. The best solution I found is to use require to extract the package, then you can get the function specifically.

    The most efficient solution I found was in an expo forum post. Reproducing the pattern applied to this problem here:

    import MapView, { Marker } from "react-native-maps";
    
    let PROVIDER_GOOGLE;
    if (Platform.OS == 'android') {
      PROVIDER_GOOGLE = require('react-native-maps').PROVIDER_GOOGLE;
    }