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

情到浓时终转凉″ 提交于 2019-12-20 23:26:57

问题


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


回答1:


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';


来源:https://stackoverflow.com/questions/44851502/relative-import-of-platform-specific-ios-android-typescript-files-for-react-nati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!