Vue 中的渐进式 Web 应用
使用 Vite 让你的 Vue 应用成为 PWA
¥Making your Vue 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.js
或 vite.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.
有关如何部署 PWA 的信息,请参阅 Vite 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
从 Ionic CLI v7 开始,Ionic Vue 入门应用随 Vite 而不是 Vue CLI 一起提供。Vite 使用说明见 使用 Vite 让你的 Vue 应用成为 PWA。
¥As of Ionic CLI v7, Ionic Vue starter apps ship with Vite instead of Vue CLI. See Making your Vue app a PWA with Vite for Vite instructions.
PWA 的两个主要要求是 服务工作进程 和 Web 应用清单。虽然可以手动将这两者添加到应用中,但 Vue 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, the Vue CLI has some utilities for adding this for you.
对于现有项目,你可以运行 vue add
命令安装 Vue 的 PWA 插件。
¥For existing projects, you can run the vue add
command to install the PWA plugin for Vue.
vue add pwa
如果你已经进行了更改,请务必在 Git 中提交它们。
¥If you have changes already in place, be sure to commit them in 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 将在构建时创建的 Service Worker。在这里,我们可以自定义当 Service Worker 检测到更新、网络连接发生变化或收到错误时用户将获得的体验。
¥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);
},
});
}
生成的 Service Worker 基于 Workbox 的 webpack 插件,默认设置为使用 GenerateSW()
。这意味着在构建时,Workbox 将自动为其处理的所有文件生成 Service Worker 缓存。
¥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 Static Web Apps。所有这些都需要完成类似的设置过程。在本指南中,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 托管为渐进式 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.
"你想使用什么 作为你的公共目录?" 输入 "dist"。
¥**"What do you want to use as your public directory?"** Enter "dist".
回答下一个问题将确保路由、硬重载和深度链接在应用中正常工作:
¥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": "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.