Skip to main content

React 中的渐进式 Web 应用

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

🌐 Making your React app a PWA with Vite

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

要开始,请安装 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.

请参阅 Vite PWA “部署” 指南 以获取有关如何部署你的 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

note

从 Ionic CLI v7 开始,Ionic React 启动应用使用 Vite 而不是 Create React App。有关 Vite 的说明,请参阅 使用 Vite 将 React 应用变为 PWA

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

在你的应用的 index.ts 中,有一个对 serviceWorker.unregister() 函数的调用。CRA 提供的基础版本将服务工作者作为可选功能,因此必须启用它。要启用,请调用 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.

note

默认情况下,React 应用包自带 Ionic 徽标作为应用图标。请确保更新清单以使用正确的应用名称,并更换图标。

note

像服务工作者(Service Workers)和许多 JavaScript API(例如地理位置)这样的功能需要应用在安全环境中托管。在通过托管服务部署应用时,请注意,为了充分利用服务工作者,需要使用 HTTPS。

服务工作线程配置

🌐 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 托管为渐进式网页应用提供了许多好处,包括由于 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
note

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

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

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

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

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

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

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

“你想用什么作为你的公共目录?” 输入“build”.

note

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

配置为单页应用(将所有 URL 重写到 /index.html)? 输入“是”。

“文件 build/index.html 已经存在。要覆盖吗?” 输入 “否”。

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

你想为哪个 GitHub 仓库设置 GitHub 工作流? 请输入你的项目名称。

是否在每次部署前设置工作流以运行构建脚本? 输入“是”。

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

当 PR 被合并时,是否将自动部署设置到你的网站直播通道? 输入“是”。

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

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

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

最后需要做的是确保缓存头设置正确。为此,请在 firebase.json 文件中添加 headers 片段。完整的 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.