Skip to main content

Vue 中的渐进式 Web 应用

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

🌐 Making your Vue 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 vue from '@vitejs/plugin-vue';
import { VitePWA } from 'vite-plugin-pwa';

export default defineConfig({
plugins: [vue(), 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.

使用 Vue CLI 将你的 Vue 应用打造为 PWA

🌐 Making your Vue app a PWA with Vue CLI

note

从 Ionic CLI v7 开始,Ionic Vue 入门应用使用 Vite 而不是 Vue CLI。有关 Vite 的说明,请参见 使用 Vite 将你的 Vue 应用变成 PWA

PWA 的两个主要要求是 服务工作者Web 应用清单。虽然可以手动将这两者添加到应用中,但 Vue CLI 提供了一些为你添加它们的工具。

对于现有项目,你可以运行 vue add 命令来为 Vue 安装 PWA 插件。

🌐 For existing projects, you can run the vue add command to install the PWA plugin for Vue.

vue add pwa
note

如果你已经进行了更改,请务必在 Git 中提交它们。

一旦完成,Vue 的 CLI 将创建一个新的 registerServiceWorker.ts 文件并将其导入我们的 main.ts 中。

🌐 Once this is completed, Vue's CLI will have created a new registerServiceWorker.ts file and imported it into our main.ts.

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
// Added by the CLI
import './registerServiceWorker';

createApp(App).use(router).mount('#app');

registerServiceWorker.ts 文件将指向 CLI 在构建时创建的服务工作者。在这里,我们可以自定义用户在服务工作者检测到更新、网络连接变化或收到错误时的体验。

🌐 The registerServiceWorker.ts file will point to a service worker that the CLI will create at build time. Inside of here we can customize the experience users will have when the service worker detects an update, change in network connectivity, or receives an error.

import { register } from 'register-service-worker';

if (process.env.NODE_ENV === 'production') {
register(`${process.env.BASE_URL}service-worker.js`, {
ready() {
console.log(
'App is being served from cache by a service worker.\n' + 'For more details, visit https://goo.gl/AFskqB'
);
},
registered() {
console.log('Service worker has been registered.');
},
cached() {
console.log('Content has been cached for offline use.');
},
updatefound() {
console.log('New content is downloading.');
},
updated() {
console.log('New content is available; please refresh.');
},
offline() {
console.log('No internet connection found. App is running in offline mode.');
},
error(error) {
console.error('Error during service worker registration:', error);
},
});
}

生成的服务工作者是基于 Workbox 的 webpack 插件,并且默认设置为使用 GenerateSW()。这意味着在构建时,Workbox 会自动为它处理的所有文件生成服务工作者缓存。

🌐 The service worker that is generated is based on Workbox's webpack plugin, and by default is setup to use GenerateSW(). Meaning that at build time, Workbox will automatically generate a service worker cache for all the files it processes.

如果你想配置这个并更改默认行为,请查看 GitHub 上的 PWA 插件文档

🌐 If you want to configure this and change the default behavior, checkout the PWA plugin docs on GitHub.

显现

🌐 Manifest

除了 service worker 外,Vue PWA 插件还负责为你的应用创建一个清单文件。默认情况下,CLI 将生成一个包含以下条目的清单。

🌐 In addition to the service worker, the Vue PWA plugin also is responsible for creating a manifest file for your app as well. By default, the CLI will generate a manifest that contains the following entries.

{
"name": "pwa-test",
"short_name": "pwa-test",
"theme_color": "#4DBA87",
"icons": [
{
"src": "./img/icons/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "./img/icons/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "./img/icons/android-chrome-maskable-192x192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "./img/icons/android-chrome-maskable-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
],
"start_url": ".",
"display": "standalone",
"background_color": "#000000"
}

请务必更新 public/img/icons 中的图标以匹配你自己的品牌。如果你想自定义主题颜色或名称,请务必阅读 GitHub 上的 PWA 插件文档

🌐 Be sure to update the icons in public/img/icons to match your own brand. If you wanted to customize the theme color or name, be sure to read the PWA plugin docs on GitHub.

部署

🌐 Deploying

你可以使用各种主机,例如 Firebase、Vercel、Netlify,甚至 Azure 静态 Web 应用。所有这些都需要完成类似的设置过程。在本指南中,将以 Firebase 作为托管示例。除了本指南外,Vue CLI 文档 也有一个关于如何部署到各种提供商的指南。

🌐 You can use various hosts like Firebase, Vercel, Netlify, or even Azure Static Web Apps. All will have similar setup processes that need to be completed. For this guide, Firebase will be used as the hosting example. In addition to this guide, the Vue CLI docs also have a guide on how to deploy to various providers.

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 网站上创建的项目。

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

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": "dist",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
],
"headers": [
{
"source": "/**",
"headers": [
{
"key": "Cache-Control",
"value": "public, max-age=31536000"
}
]
},
{
"source": "precache-manifest.*.js",
"headers": [
{
"key": "Cache-Control",
"value": "no-cache"
}
]
},
{
"source": "service-worker.js",
"headers": [
{
"key": "Cache-Control",
"value": "no-cache"
}
]
}
]
}
}

有关 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

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

🌐 Last, deploy the app by running:

firebase deploy

完成后,该应用将上线。

🌐 After this completes, the app will be live.