针对React-Native应用程序的平台特定ios / android typescript文件的相对导入 [英] Relative import of platform specific ios/android typescript files for React-Native app

查看:265
本文介绍了针对React-Native应用程序的平台特定ios / android typescript文件的相对导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于React-Native平台的2个不同设计的组件: MyComponent.ios.tsx MyComponent.android。 tsx

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

虽然当我将我的组件导入 MyView.tsx 时,它会抱怨。

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


MyView.tsx(5,38):错误TS2307:找不到模块'./MyComponent'。

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

我试图将我的 tsconfig 文件路径修改为以下内容:

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?

谢谢

推荐答案

基本上这种方法不能用于一个原因,一旦你的ts文件被转换,相对路径不再存在,编译器不再需要添加.ios或.android并停止抱怨,所以输出在阅读纯JS时,它不会在react-native方面工作。

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.

我通过在同一文件夹中创建一个typings(MyComponent.d.ts)文件来实现它,例如:

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

这篇关于针对React-Native应用程序的平台特定ios / android typescript文件的相对导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆