vue项目中使用service-worker监测项目更新

注意点:打包的时候只有当打包环境为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
      }
    }
  })
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_陌默

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值