The issue at hand:
In my react native project, I am using a custom hook that has platform-specific code. I need to import this hook based on the platform in use. When I import it as
import useWifi from 'hooks/use-wifi.android';
, everything works smoothly on Android.
Approach taken so far:
Following React Native's guidelines for platform specific code, I have organized my file structure as shown below:
...
hooks
...
use-wifi.android.ts
use-wifi.ios.ts
...
However, when I attempt to import it like
import useWifi from 'hooks/use-wifi';
, TypeScript type checking fails and Metro throws the following error:
error: Error: Unable to resolve module `hooks/use-wifi` from `src/screens/home/index.tsx`: hooks/use-wifi could not be found within the project.
As an attempt to resolve this issue, I created a use-wifi.d.ts
file with the contents:
export * from './use-wifi.android';
export * from './use-wifi.ios';
This allowed me to pass the TypeScript compiler checks, but Metro still encounters issues during bundling.
Although one solution could be to have a single hooks/use-wifi.ts
file and handle the code splitting there, I am exploring if there is a way to achieve this through separate platform-specific files.