# 四.性能优化(pwa)

前言

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

# 1.manifest.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"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 2.index.html 中

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

# 3.registerServiceWorker.js

https 环境下

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)
    },
  })
}
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
31
32

# 4.vue.config.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]
              }
          }
        }
      ]
    }
  }
}
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