注意点:打包的时候只有当打包环境为production的时候,打包时才会生成service-worker.js,且发布之后只有在https和localhost中可以使用。
具体使用方法如下:
1. 使用插件register-service-worker注册
registerServiceWorker.js(与main.js同级)
/* eslint-disable no-console */
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 (registration) {
// 通过定时监测功能。
setInterval(() => {
registration.update();
}, 1000);
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 (registration) {
console.log('New content is available; please refresh.')
// 这里已经将最新版下载到本地,询问用户是否立即刷新
var res = 'confirm("是否立即更新")'
if(res) {
window.location.reload();
}
},
offline () {
console.log('No internet connection found. App is running in offline mode.')
},
error (error) {
console.error('Error during service worker registration:', error)
}
})
}
2.引用
import './registerServiceWorker';
3.更新配置
vue.config.js
module.exports = defineConfig({
transpileDependencies: true,
productionSourceMap: false,
lintOnSave: false,
pwa: {
workboxOptions: {
skipWaiting: true, // 是否立即更新
clientsClaim: true
}
}
})