Skip to content

十一.PWA

前言

在 vue 项目中 PWA 的应用场景,以及 pwa 的用法以及注意事项

1.manifest.json

json
{
  "name": "wc--movies", // 导航显示的名字
  "short_name": "wc", // app的名字
  "start_url": ".",
  "icon": [
    {
      // app图标,会根据不一样的系统进行适配
      "src": "/public/img/icons/android-chrome-128x128.png",
      "sizes": "128x128",
      "type": "image/png"
    },
    {
      "src": "/public/img/icons/android-chrome-192x192.png", // 大小
      "sizes": "192x192", // 格式
      "type": "image/png"
    }
  ], //导航界面的背景颜色
  "background_color": "white", //手机最上方显示运营商及电量、时间等这一栏的颜色
  "theme_color": "white", //页面显示效果为没有地址栏和底部状态栏
  "display": "standalone"
}

2.index.html 中

html
<link rel="manifest" href="/manifest.json" />

3.registerServiceWorker.js

https 环境下

js
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)
    },
  })
}

4.vue.config.js

js
pwa: {
    workboxPluginMode: 'GenerateSW', // 也可以定义为‘InjectManifest’模式。但是需自己写SW.js文件进行配置
    workboxOptions: {
        importWorkboxFrom: 'cdn', //从''cdn"导入workbox,也可以‘local’
        skipWaiting: true, // 安装完SW不等待直接接管网站
        clientsClaim: true,
        navigateFallback: '/index.html',
        exclude: [/\.(?:png|jpg|jpeg|svg)$/], //在预缓存中排除图片
        // 定义运行时缓存
        runtimeCaching: [
            {
                urlPattern: new RegExp('^https://cdn'),
                handler: 'NetworkFirst',
                options: {
                    networkTimeoutSeconds: 20,
                    cacheName: 'cdn-cache',
                    cacheableResponse: {
                        statuses: [200]
                    }
                }
            }
        ]
    }
}