首页 > 解决方案 > 如何在 vue cli3 中缓存服务工作者中的 api 和资产

问题描述

import { register } from 'register-service-worker'
import pwa from '@vue/cli-plugin-pwa'

if (process.env.NODE_ENV === 'development') {
// if (process.env.NODE_ENV === 'production') {
console.log(pwa)
register(`${process.env.BASE_URL}service-worker.js`, {
ready () {
    console.log(
      'App is being served from cache by a service worker.\n'
    )
  },
  cached () {
    console.log('Content has been cached for offline use.')
  },
  updated () {
    console.log('New content is available; please refresh.')
  },
  offline () {
    console.log('No internet connection found. App is running in 
    offline mode.')
  },
  error (error) {
    console.error('Error during service worker registration:', error)
  }
})
}

这是我的 registerserviceworker.js。我试图在这个文件中实现,但我无法在其中添加文件和 api。

标签: javascriptvue.jsservice-workervue-cli

解决方案


您必须使用 vue.config.js 的 PWA 对象内的“workboxOptions”。像这样:

module.exports = {
    pwa: {
        [...]
        workboxOptions: {
            runtimeCaching: [{
                urlPattern: new RegExp('^https://yourpathtothe.api/'),
                handler: 'networkFirst',
                    options: {
                    networkTimeoutSeconds: 20,
                    cacheName: 'api-cache',
                    cacheableResponse: {
                        statuses: [0, 200],
                    },
                },
            }]
        }
    },

推荐阅读