为 Vue 项目开启 PWA
之前的网络上的教程都是 vue/cli 的, 经过我的一番摸索, 终于弄明白了 vite+vue3+pwa 的正确打开方式
-
安装
vite-plugin-pwa
npm i vite-plugin-pwa -D
-
配置
vite-plugin-pwa
1
2
3
4import { VitePWA } from "vite-plugin-pwa";
export default defineConfig({
plugins: [VitePWA({ registerType: "autoUpdate" })],
});
使 PWA 可安装
一开始配置好后, 浏览器并没有提示可以安装, 经过一晚上的摸索(看文档), 最终总结如下
使 PWA 可安装的前置要求: https://vite-pwa-org.netlify.app/guide/pwa-minimal-requirements.html
必须?同时满足以下条件
-
index.html
中的<head>
标签中配置如下条目viewport
title
标签description
favicon
apple-touch-icon
mask-icon
theme-color
-
Manifest
清单文件中有如下配置- a scope: omitted here for simplicity, the
vite-plugin-pwa
plugin will use theVite
base option to configure it (default is/
) - a name
- a short description
- a description
- a
theme_color
: must match the configured one onEntry Point theme-color
- an icon with
192x192
size - an icon with
512x512
size
- a scope: omitted here for simplicity, the
-
也就是
vite.config.js
进行如下配置1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30import { VitePWA } from "vite-plugin-pwa";
export default defineConfig({
plugins: [
VitePWA({
includeAssets: [
"favicon.ico",
"apple-touch-icon.png",
"masked-icon.svg",
],
manifest: {
name: "My Awesome App",
short_name: "MyApp",
description: "My Awesome App description",
theme_color: "#ffffff",
icons: [
{
src: "pwa-192x192.png",
sizes: "192x192",
type: "image/png",
},
{
src: "pwa-512x512.png",
sizes: "512x512",
type: "image/png",
},
],
},
}),
],
}); -
配置
robots.txt
1
2User-agent: *
Allow: / -
服务端满足以下要求 https://vite-pwa-org.netlify.app/deployment/
- serve
manifest.webmanifest
withapplication/manifest+json
mime type - 必须使用
https
http
重定向https
- serve
为 Vue 项目开启 PWA