Skip to main content

React 中的渐进式 Web 应用

使用 Vite 让你的 React 应用成为 PWA

¥Making your React app a PWA with Vite

PWA 的两个主要要求是 服务工作进程Web 应用清单。虽然可以手动将这两者添加到应用中,但我们建议使用 Vite PWA 插件

¥The two main requirements of a PWA are a Service Worker and a Web Application Manifest. While it's possible to add both of these to an app manually, we recommend using the Vite PWA Plugin instead.

首先,安装 vite-plugin-pwa 软件包:

¥To get started, install the vite-plugin-pwa package:

npm install -D vite-plugin-pwa

接下来,更新 vite.config.jsvite.config.ts 文件并添加 vite-plugin-pwa

¥Next, update your vite.config.js or vite.config.ts file and add vite-plugin-pwa:

import { defineConfig } from 'vite';


import react from '@vitejs/plugin-react';


import { VitePWA } from 'vite-plugin-pwa';

export default defineConfig({
plugins: [react(), VitePWA({ registerType: 'autoUpdate' })],
});

这种最小的配置允许你的应用在构建时生成 Web 应用清单和服务工作线程。

¥This minimal configuration allows your application to generate the Web Application Manifest and Service Worker on build.

有关配置 Vite PWA 插件的更多信息,请参阅 Vite PWA "新手上路" 指南

¥For more information on configuring the Vite PWA Plugin, see the Vite PWA "Getting Started" Guide.

有关如何部署 PWA 的信息,请参阅 Vite PWA "部署" 指南

¥See the Vite PWA "Deploy" Guide for information on how to deploy your PWA.

使用 Create React App 让你的 React 应用成为 PWA

¥Making your React app a PWA with Create React App

注意

从 Ionic CLI v7 开始,Ionic React 入门应用随 Vite 一起提供,而不是 Create React App。Vite 使用说明见 使用 Vite 让你的 React 应用成为 PWA

¥As of Ionic CLI v7, Ionic React starter apps ship with Vite instead of Create React App. See Making your React app a PWA with Vite for Vite instructions.

PWA 的两个主要要求是 服务工作进程Web 应用清单。虽然可以手动将这两者添加到应用中,但 Create React App (CRA) 和 Ionic CLI 的基础项目已经提供了这一点。

¥The two main requirements of a PWA are a Service Worker and a Web Application Manifest. While it's possible to add both of these to an app manually, a base project from Create React App (CRA) and the Ionic CLI provides this already.

在你的应用的 index.ts 中,有对 serviceWorker.unregister() 函数的调用。CRA 提供的基础将 Service Worker 作为可选功能,因此必须启用它。要启用,请调用 serviceWorker.register()

¥In the index.ts for your app, there is a call to a serviceWorker.unregister() function. The base that CRA provides has service workers as an opt-in feature, so it must be enabled. To enable, call serviceWorker.register().

import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import * as serviceWorkerRegistration from './serviceWorkerRegistration';

const container = document.getElementById('root');
const root = createRoot(container!);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://cra.link/PWA
serviceWorkerRegistration.register();

添加此包后,运行 ionic buildbuild 目录将准备好部署为 PWA。

¥Once this package has been added, run ionic build and the build directory will be ready to deploy as a PWA.

注意

默认情况下,React 应用包带有应用图标的 Ionic 徽标。请务必更新清单以使用正确的应用名称并替换图标。

¥By default, react apps package comes with the Ionic logo for the app icons. Be sure to update the manifest to use the correct app name and also replace the icons.

注意

Service Workers 和许多 JavaScript API(例如地理位置)等功能要求应用托管在安全的上下文中。通过托管服务部署应用时,请注意需要 HTTPS 才能充分利用 Service Worker。

¥Features like Service Workers and many JavaScript APIs (such as geolocation) require the app to be hosted in a secure context. When deploying an app through a hosting service, be aware that HTTPS will be required to take full advantage of Service Workers.

服务工作线程配置

¥Service Worker configuration

默认情况下,CRA/React 脚本附带基于 Workbox 的 Webpack 插件 的预配置 Service Worker 设置。这利用了缓存优先策略,这意味着即使网络返回应用的较新版本,你的应用也会从缓存加载。

¥By default, CRA/React Scripts come with a preconfigured Service Worker setup based on Workbox's Webpack plugin. This utilizes a cache-first strategy, meaning that your app will load from a cache, even if the network returns a newer version of the app.

由于 CRA/React Scripts 的性质,其配置是 React Scripts 的内部配置,这意味着如果不从 React Scripts 中弹出,就无法对其进行自定义。目前,Ionic CLI 不支持弹出的 React 应用,因此如果执行此操作,你将需要使用 npm/yarn 脚本而不是 Ionic CLI。

¥Because of the nature of CRA/React Scripts, the configuration for this is internal to React Scripts, meaning that it cannot be customized without ejecting from React Scripts. Currently, the Ionic CLI does not support an ejected React App, so if this action is taken, you'll need to use npm/yarn scripts instead of the Ionic CLI.

部署

¥Deploying

Firebase

Firebase 托管为渐进式 Web 应用提供了许多好处,包括由于 CDN 实现的快速响应时间、默认启用的 HTTPS 以及对 HTTP2 推送 的支持。

¥Firebase hosting provides many benefits for Progressive Web Apps, including fast response times thanks to CDNs, HTTPS enabled by default, and support for HTTP2 push.

首先,如果尚未可用,请在 Firebase 中使用 创建项目

¥First, if not already available, create the project in Firebase.

接下来,在终端中安装 Firebase CLI:

¥Next, in a Terminal, install the Firebase CLI:

npm install -g firebase-tools
注意

如果你是第一次使用 firebase-tools,请使用 firebase login 命令登录你的 Google 账户。

¥If it's the first time you use firebase-tools, login to your Google account with firebase login command.

安装 Firebase CLI 后,在 Ionic 项目中运行 firebase init。CLI 提示:

¥With the Firebase CLI installed, run firebase init within your Ionic project. The CLI prompts:

"你想为此文件夹设置哪些 Firebase CLI 功能?" 选择“托管:配置 Firebase 托管文件并(可选)设置 GitHub Action 部署”。

¥**"Which Firebase CLI features do you want to set up for this folder?"** Choose "Hosting: Configure files for Firebase Hosting and (optionally) set up GitHub Action deploys".

创建一个新的 Firebase 项目或选择现有项目。

¥Create a new Firebase project or select an existing one.

"为此目录选择默认 Firebase 项目:" 选择你在 Firebase 网站上创建的项目。

¥**"Select a default Firebase project for this directory:"** Choose the project you created on the Firebase website.

"你想使用什么作为你的公共目录?" 输入 "build"。

¥**"What do you want to use as your public directory?"** Enter "build".

注意

回答下一个问题将确保路由、硬重载和深度链接在应用中正常工作:

¥Answering this next question will ensure that routing, hard reload, and deep linking work in the app:

配置为单页应用(将所有 url 重写为/index.html)?"进入" 是”。

¥Configure as a single-page app (rewrite all urls to /index.html)?" Enter "Yes".

"File build/index.html already exists.覆盖?"进入" 否”。

¥**"File build/index.html already exists. Overwrite?"** Enter "No".

使用 Github 设置自动构建和部署?输入 "是的"。

¥Set up automatic builds and deploys with Github? Enter "Yes".

你想为哪个 GitHub 存储库设置 Github 工作流程?输入你的项目名称。

¥For which GitHub repository would you like to set up a Github Workflow? Enter your project name.

设置工作流程以在每次部署之前运行构建脚本?输入 "是的"。

¥Set up the workflow to run a build script before every deploy? Enter "Yes".

每次部署之前应运行什么脚本?输入 npm ci && npm run build

¥What script should be run before every deploy? Enter npm ci && npm run build.

合并 PR 时是否设置自动部署到你网站的实时通道?输入 "是的"。

¥Set up automatic deployment to your sites live channel when a PR is merged? Enter "Yes".

与你的网站直播通道关联的 get hooked 分支的名称是什么?输入项目的主分支名称。

¥What is the name of the get hooked branch associated with your sites live channel? Enter your project's main branch name.

生成 firebase.json 配置文件,配置应用以进行部署。

¥A firebase.json config file is generated, configuring the app for deployment.

最后需要做的就是确保缓存标头设置正确。为此,请将 headers 代码段添加到 firebase.json 文件中。完整的 firebase.json 看起来像:

¥The last thing needed is to make sure caching headers are being set correctly. To do this, add a headers snippet to the firebase.json file. The complete firebase.json looks like:

{
"hosting": {
"public": "build",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
],
"headers": [
{
"source": "/**",
"headers": [
{
"key": "Cache-Control",
"value": "public, max-age=31536000"
}
]
}
]
}
}

有关 firebase.json 属性的更多信息,请参阅 Firebase 文档

¥For more information about the firebase.json properties, see the Firebase documentation.

接下来,通过运行以下命令构建应用的优化版本:

¥Next, build an optimized version of the app by running:

ionic build --prod

最后,通过运行以下命令来部署应用:

¥Last, deploy the app by running:

firebase deploy

完成后,该应用将上线。

¥After this completes, the app will be live.