与 Expo 一起开发网站
了解如何开发网络应用,以便构建通用应用。
Expo 对使用 React 构建全栈网站提供一流的支持。Expo 网站可以进行静态渲染以优化 SEO 和性能,或者进行客户端渲染,以在浏览器中提供更接近应用的体验。
🌐 Expo has first-class support for building full-stack websites with React. Expo websites can be statically rendered for SEO and performance, or client-rendered for a more app-like experience in the browser.
使用 React Native for web 的 <Text> 组件在任何平台上呈现文本。
import { Text } from 'react-native'; export default function Page() { return <Text>Home page</Text>; }
用于 Web 的 React Native(RNW)是一组组件库,例如 <View> 和 <Text>,它们封装了 react-dom 原语,如 <div>、<p> 和 <img>。在开发 Web 应用时,RNW 是可选的,因为你可以直接使用 React DOM,但我们通常建议在跨平台构建时使用它,因为它可以最大化代码重用。
React Native for web 被用来驱动整个 X 网站。
或者,你可以编写仅用于网页的 React DOM 组件,例如 <div>、<p> 等,但这些组件无法在原生平台上渲染。
export default function Page() { return <p>Home page</p>; }
Expo 完全支持构建仅适用于网页的组件,但你可能希望组织代码,以更好地支持同时为网页和原生平台构建。更多信息请参见 平台特定模块。
Expo SDK 中的所有库都是为了支持浏览器和服务器渲染环境(如适用)而构建的。这些库也针对它们所面向的各个平台进行了优化。
🌐 All of the libraries in the Expo SDK are built to support both browser and server rendering environments (when applicable). Libraries are also optimized for the individual platforms they target.
开发功能如快速刷新、调试、环境变量和打包也都是完全通用的,从而实现统一的开发者体验。Expo CLI在构建生产版本时会自动为各个平台优化代码,使用诸如平台摇树优化等技术。
🌐 Development features like Fast Refresh, debugging, environment variables, and bundling are also fully universal, enabling a unified developer experience. Expo CLI automatically optimizes code for individual platforms when you build for production, using techniques like platform shaking.
入门
🌐 Getting started
安装网络依赖
🌐 Install web dependencies
- npx expo install react-dom react-native-web @expo/metro-runtime你的应用还没有使用 expo 包吗?
如果你还没有将 Expo 添加到你的 React Native 应用中,你可以选择安装 Expo 模块(推荐)或者只安装 expo 包并配置应用入口文件。这将允许你针对 Web 平台,但不会包含对 Expo SDK 的支持。
🌐 If you haven't added Expo to your React Native app yet, you can either install Expo modules (recommended) or just install the expo package and configure the app entry file. This will allow you to target web, but it will not include support for the Expo SDK.
- 在你的项目中安装 Expo CLI:
- npm install expo- 修改入口文件以使用
registerRootComponent替代AppRegistry.registerComponent:
| 1 | import {AppRegistry} from 'react-native'; | |
| 2 | import {name as appName} from './app.json'; | |
| 1 | import {registerRootComponent} from 'expo'; | |
| 3 | 2 | import App from './App'; |
| 4 | 3 | |
| 5 | AppRegistry.registerComponent(appName, () => App); | |
| 4 | registerRootComponent(App); |
启动开发服务器
🌐 Start the dev server
你现在可以启动开发服务器,并在浏览器中进行开发,使用:
🌐 You can now start the dev server and develop in the browser with:
- npx expo start --web该应用可以导出为具有以下功能的生产网站:
🌐 The app can be exported as a production website with:
- npx expo export --platform web下一章
🌐 Next
使用 Expo Router 构建路由和导航。
使用 Expo Router 将你的网站渲染为静态 HTML,以提高 SEO 和性能。
EAS Hosting 是部署你的 Expo Router 和 React Native 网页应用的最佳方式,支持自定义域名、SSL 等功能。
为你的项目自定义 Metro 打包器。