如何在Vue CLI3中在Service Worker中缓存API和资产

时间:2018-08-03 08:51:49

标签: javascript vue.js service-worker vue-cli

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。

1 个答案:

答案 0 :(得分:0)

您必须在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],
                    },
                },
            }]
        }
    },