使用workbox在webpack里配置serviceworker(2022-02-15)

1、本项目是在react的webpack项目里使用workbox来配置serviceworker

2、仅支持https和本地localhost环境

本文仅供快速配置参考,其余详细信息请查看谷歌官方文档
https://developers.google.cn/web/tools/workbox/modules

1、基础用法

安装:

npm i workbox-webpack-plugin workbox-core workbox-routing workbox-strategies workbox-precaching workbox-expiration workbox-cacheable-response -D
    "workbox-cacheable-response": "^6.4.2",
    "workbox-core": "^6.4.2",
    "workbox-expiration": "^6.4.2",
    "workbox-precaching": "^6.4.2",
    "workbox-routing": "^6.4.2",
    "workbox-strategies": "^6.4.2",
    "workbox-webpack-plugin": "^6.4.2"

1、准备一个serviceworker.js模板文件,并根据官方文档配置相关设置

import { skipWaiting, clientsClaim, cacheNames, setCacheNameDetails } from 'workbox-core'
import { ExpirationPlugin } from 'workbox-expiration'
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching'
import { NavigationRoute, registerRoute } from 'workbox-routing'
import { StaleWhileRevalidate, CacheFirst } from 'workbox-strategies'

// 基础信息设置

setCacheNameDetails({
    prefix: 'ReactMobileH5',
    suffix: 'v1.0', //控制版本
    precache: 'install-time',
    runtime: 'run-time',
    googleAnalytics: 'ga',
});


skipWaiting()
clientsClaim()

precacheAndRoute(self.__WB_MANIFEST)

2、在webpack配置中初始化

const { InjectManifest } = require('workbox-webpack-plugin')

new InjectManifest({
    swSrc: path.resolve('src/serviceworker.js'),
    swDest: path.resolve(routePreName, 'serviceworker.js'),
  })

3、在页面js里注册

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {    navigator.serviceWorker.register('/ReactMobileH5/serviceworker.js').then(registration => {
      console.log('sw注册成功了 ', registration);
    }).catch(registrationError => {
      console.log('SW注册失败 ', registrationError);
    });
  });
}

4、打包后在本地localhost环境下运行项目,并在浏览器中查看缓存使用

2、配置路由

更新中

你可能感兴趣的:(使用workbox在webpack里配置serviceworker(2022-02-15))