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

后端 未结 1 1402
迷失自我
迷失自我 2021-02-08 10:31

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

Althou

1条回答
  •  醉话见心
    2021-02-08 10:44

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

    0 讨论(0)
提交回复
热议问题