I am working on an app, with a web version (React DOM) and a Native one.
I created an internal "core" package with some core shared between the two platforms. For some modules in my core package, I need to have different implementations between the browser version and the native one.For example I need to handle Base64 data, so I have a base64.ts
file with the browser implementation:
const { atob, btoa } = windowexport { atob, btoa }
And a React Native implementation in base64.native.ts
using an external library :
export { decode as atob, encode as btoa } from "base-64"
And I can use it in my code like this:
import { btoa } from "core/base64"
This works fine on both platforms, as the React Native Metro bundler prefers the .native.ts
file and uses it.
But the Typescript compiler emits an error when checking my React Native project because when it encounters the imports it resolves it with the web-based implementation (base64.ts
) which triggers an error as btoa
does not exist in the global space in React Native.
I have the same issue with other modules with different web & native implementations, like when the web module uses window
and the RN module uses native functions.
What is the supported way of handling cross-platform implementations like this?