pwa

@vuepress/plugin-pwa

使你的 VuePress 站点成为一个 渐进式 Web 应用 (PWA)在新窗口打开.

该插件使用 workbox-build在新窗口打开 来生成 Service Worker 文件,并通过 register-service-worker在新窗口打开 来注册 Service Worker 。

安装

npm i -D @vuepress/plugin-pwa@next
1

Web App Manifests

为了使你的网站符合 PWA 的要求,你需要创建一个 Web app manifests在新窗口打开 文件,并且为你的 PWA 设置图标、颜色等信息。

你需要将你的 Manifest 文件和图标放置在 Public 目录 下。在下述的示例中,我们假设你正在使用默认的 Public 目录 .vuepress/public

  1. 创建 Manifest 文件

通常是 .vuepress/public/manifest.webmanifest

{
  "name": "VuePress",
  "short_name": "VuePress",
  "description": "Vue-powered Static Site Generator",
  "start_url": "/index.html",
  "display": "standalone",
  "background_color": "#fff",
  "theme_color": "#3eaf7c",
  "icons": [
    {
      "src": "/images/icons/android-chrome-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "/images/icons/android-chrome-384x384.png",
      "sizes": "384x384",
      "type": "image/png"
    }
  ]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  1. 生成 PWA 图标

为了提高你的 PWA 的可用性,你需要生成一些图标,并将它们放置在 Public 目录下。

确保图标的路径匹配 Manifest 文件中的 icons 字段:

  • .vuepress/public/images/icons/android-chrome-192x192.png
  • .vuepress/public/images/icons/android-chrome-384x384.png

提示

一些工具可以帮助你做这些事。比如 Favicon Generator在新窗口打开 可以帮助你生成图片以及一个 Manifest 文件样例。

  1. 设置 Head 中的标签

你还需要通过 head 配置项来设置一些标签,用来 部署你的 Manifest 文件在新窗口打开

module.exports = {
  head: [
    ['link', { rel: 'manifest', href: '/manifest.webmanifest' }],
    ['meta', { name: 'theme-color', content: '#3eaf7c' }],
    // ...其他标签
  ]
}
1
2
3
4
5
6
7

配置项

该插件的配置项可以接收 workbox-build 中 generateSW 方法在新窗口打开 除了 globDirectoryswDest 以外的所有参数。

比如,你可以设置 skipWaiting: true ,这将在新的 Service Worker 就绪之后立即激活它:

module.exports = {
  plugins: [
    [
      '@vuepress/pwa',
      {
        skipWaiting: true,
      },
    ],
  ],
}
1
2
3
4
5
6
7
8
9
10

但是如果你不设置 skipWaiting 或设置为 false ,你就需要手动激活新的 Service Worker 。

  • 对于用户,你可以配合我们提供的 pwa-popup 插件一起使用。
  • 对于开发者,你可以使用该插件提供的 Composition API 来控制 Service Worker 的行为。

serviceWorkerFilename

  • 类型: string

  • 默认值: 'service-worker.js'

  • 详情:

    生成的 Service Worker 文件路径,该路径是 dest 目录的相对路径。

    Service Worker 文件只会在 build 模式下生成。

Composition API

usePwaEvent

import { usePwaEvent } from '@vuepress/plugin-pwa/lib/client'

export default {
  setup() {
    const event = usePwaEvent()
    event.on('ready', (registration) => {
      console.log('Service worker 已经生效。')
    })
  },
}
1
2
3
4
5
6
7
8
9
10

useSkipWaiting

  • 参数:
参数类型描述
registrationServiceWorkerRegistration你想要激活的 Service Worker 的 Registration
import {
  usePwaEvent,
  useSkipWaiting,
} from '@vuepress/plugin-pwa/lib/client'

export default {
  setup() {
    const event = usePwaEvent()
    event.on('updated', (registration) => {
      console.log('在 Waiting 状态的 Service Worker 已经就绪。')
      // 激活 Waiting 状态的 Service Worker
      useSkipWaiting(registration)
    })
  },
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15