1奸腺、本項(xiàng)目是在react的webpack項(xiàng)目里使用workbox來(lái)配置serviceworker
2血久、僅支持https和本地localhost環(huán)境
本文僅供快速配置參考,其余詳細(xì)信息請(qǐng)查看谷歌官方文檔
https://developers.google.cn/web/tools/workbox/modules
1氧吐、基礎(chǔ)用法
安裝:
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、準(zhǔn)備一個(gè)serviceworker.js模板文件座慰,并根據(jù)官方文檔配置相關(guān)設(shè)置
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'
// 基礎(chǔ)信息設(shè)置
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、在頁(yè)面js里注冊(cè)
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => { navigator.serviceWorker.register('/ReactMobileH5/serviceworker.js').then(registration => {
console.log('sw注冊(cè)成功了 ', registration);
}).catch(registrationError => {
console.log('SW注冊(cè)失敗 ', registrationError);
});
});
}
4蛮粮、打包后在本地localhost環(huán)境下運(yùn)行項(xiàng)目,并在瀏覽器中查看緩存使用
2莺奔、配置路由
更新中