最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Relative import of platform specific iosandroid typescript files for React-Native app - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question asked Jun 30, 2017 at 16:53 alexmngnalexmngn 9,59720 gold badges75 silver badges136 bronze badges 2
  • How are you importing MyComponent? Is it like the following import MyComponent from '../MyComponent'; – Mμ. Commented Jul 14, 2017 at 4:12
  • Possible duplicate of Platform specific import component in react native with typescript – Jamie Birch Commented Dec 29, 2018 at 13:06
Add a comment  | 

2 Answers 2

Reset to default 11

Since TypeScript 4.7 there is now a new option to handle this for react native, but also web

{
    "compilerOptions": {
        "moduleSuffixes": [".android", ".ios", ""]
    }
}

You can read more about it here: https://www.typescriptlang.org/tsconfig#moduleSuffixes

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)

  1. 暂无评论