Import typescript files based on naming convention in React Native

Viewed 2249

So I have three ts files named as below :

  • MyModule.ios.ts
  • MyModule.android.ts
  • MyModule.ts ( this is empty )

first two files have a method named : setup() which need to run based on platform Also metro bundler will do the resolution, it will try to import .ios when building for ios and .android when building for android..

and I have another file which import this method like this :

import { setup } from 'MyModule';

the problem is, I am not sure if this will resolve the .android and .ios files. What is the proper way to do this kind of code splitting?

I find this workaround here but I was wondering if there is a better way : https://github.com/Microsoft/TypeScript/issues/8328#issuecomment-219583152

1 Answers

If you want to use separate files for iOS and Android, you need to call them MyModule.ios.ts and MyModule.android.ts extensions. The empty MyModule.ts file is not necessary.

Then just import them as if they didn't have the platform specific extensions. React Native will automatically pick up the right file based on the running platform.

import { setup } from './MyModule'; // Will automatically import either MyModule.ios.ts or MyModule.android.ts

See the documentation on this: https://facebook.github.io/react-native/docs/platform-specific-code.html#platform-specific-extensions


If you don't want to use separate files, you can use the Platform module. This is nice for small pieces of code that you want to make platform specific.

import { Platform } from 'react-native';

if(Platform.OS === 'ios') {
  // iOS specific code here
} else if(Platform.OS === 'android') {
  // Android specific code here
} else {
  // Other platform
}

See: https://facebook.github.io/react-native/docs/platform-specific-code#platform-module

Related