使用Expo 44+Typescript进行React本地web多平台设置



在Expo中为组件实现多平台设置的最简单方法是什么。我试过很多不同的方法。。它在网络上工作,但在Native上失败了,在Jest&测试库/本地react。理想情况下,我想要最少的自定义配置等(不想弹出(。我希望文件结构看起来像这样:

Component
|- index.tsx
|- Component.native.tsx
|- Component.web.tsx

我不知道如何做index.tsx。我看到有人说这样的话会起作用:

// index.tsx
// @ts-ignore
export { default } from "Component"

这不起作用,所以我做了

// index.tsx
// @ts-ignore
export { default } from "./Component"

这对网络有效,但玩笑测试显示

Cannot find './Component'
However, Jest was able to find:
'./Component.mobile.tsx'
'./Component.web.tsx'

我试过了:

// index.tsx
// @ts-ignore
import Component from "./Component";
export default Component

并且测试是相同的

本地模拟器说:

Unable to resolve module ./Component

我尝试过使用延迟加载,但这在web上不起作用。

import { lazy, Suspense } from "react";
import { Platform } from "react-native";
import Loading from "../../components/Loading";
import { ComponentType } from "./types";
const Web = lazy(() => import("./Component.web"));
const Mobile = lazy(() => import("./Component.mobile"));
const Component: ComponentType = (props) => {
const isWeb = Platform.OS === "web";
return (
<Suspense fallback={<Loading message="Loading Component" />}>
{isWeb ? <Web {...props} /> : <Mobile {...props} />}
</Suspense>
);
};
export default Component

问题

  1. 如何根据平台为组件使用不同的文件(排除构建中的其他文件(
  2. 如何在vscode中使用ts

使用Expo 44。感谢

我会使用命名导出。因此,首先在两个文件中使用相同的组件名称。接下来,我将有一个名为Component.tsx的文件和另一个Component.native.tsx。这将足以让bundler将本机文件拉为本机文件,将另一个拉为非本机文件(换句话说,web(。这应该就是你所需要的。

最新更新