We have two projects that share a API wrapper library (that we created) that makes use of the pusher-js library for websocket communication.
The API wrapper was originally built for the web version project built on NextJS, but now we wish to include it in our new React Native project. The issue is inside the API wrapper where we instantiate pusher
, we import pusher from 'pusher-js
whereas for this to work on React Native we need to import pusher from 'pusher-js/react-native
. This lib is obviously unaware of the outer usage of who installs it and just sets these things up as a convenience wrapper.
How could this be achieved within either the mobile project or should this be setup within the API lib? I've looked into module resolution via a babel plugin but not sure how this would be setup for this instance.
CodePudding user response:
You can have a platform specific file for mobile.
// pusher.ts
import pusher from 'pusher-js';
export default pusher;
// pusher.native.ts
import pusher from 'pusher-js/react-native';
export default pusher;
// whenever you need pusher
import pusher from './pusher';
React native will import from pusher.native
for you. https://reactnative.dev/docs/platform-specific-code#native-specific-extensions-ie-sharing-code-with-nodejs-and-web