Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative import of platform specific ios/android typescript files for React-Native app

I have a component that has 2 different designs based on the platform for React-Native: MyComponent.ios.tsx and MyComponent.android.tsx.

Although when I import my component into MyView.tsx, it complains.

MyView.tsx(5,38): error TS2307: Cannot find module './MyComponent'.

I have tried to modify my tsconfig file paths to the following:

"paths": {
  "*": ["*", "*.ios", "*.android"]
},

Although I still have the same problem.

Does any of you know how to resolve this problem?

Thanks

like image 390
alexmngn Avatar asked Jun 30 '17 16:06

alexmngn


Video Answer


1 Answers

Basically this approach won't work for one reason, once your ts files are transpiled, the relative path is not there anymore for the compiler to add ".ios" or ".android" and stop complaining, so the output will not work on react-native side when reading the pure JS.

I got it working by creating a typings (MyComponent.d.ts) file in the same folder, ex:

// This file exists for two purposes:
// 1. Ensure that both ios and android files present identical types to importers.
// 2. Allow consumers to import the module as if typescript understood react-native suffixes.
import DefaultIos from './MyComponent.ios';
import * as ios from './MyComponent.ios';
import DefaultAndroid from './MyComponent.android';
import * as android from './MyComponent.android';

declare var _test: typeof ios;
declare var _test: typeof android;

declare var _testDefault: typeof DefaultIos;
declare var _testDefault: typeof DefaultAndroid;

export * from './MyComponent.ios';
like image 101
Oscar Franco Avatar answered Sep 18 '22 15:09

Oscar Franco