为 Vue 项目开启 PWA

之前的网络上的教程都是 vue/cli 的, 经过我的一番摸索, 终于弄明白了 vite+vue3+pwa 的正确打开方式

  1. 安装 ​ vite-plugin-pwa

    npm i vite-plugin-pwa -D

  2. 配置 vite-plugin-pwa

    1
    2
    3
    4
    import { 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 the Vite base option to configure it (default is /)
    • a name
    • a short description
    • a description
    • a theme_color: must match the configured one on Entry Point theme-color
    • an icon with 192x192 size
    • an icon with 512x512 size
  • 也就是 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
    30
    import { 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
    2
    User-agent: *
    Allow: /
  • 服务端满足以下要求 https://vite-pwa-org.netlify.app/deployment/

    • serve manifest.webmanifest with application/manifest+json mime type
    • 必须使用 https
    • http ​ 重定向 https
作者

cuicui

发布于

2023-02-20

更新于

2023-04-23

许可协议

评论