From f384103e55b2109f8a6302fd4dcbeed13530163d Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Fri, 17 Nov 2017 14:00:59 +0330 Subject: [PATCH] fix(workbox): use regexp for runtimeCaching. fixes #14. --- packages/workbox/index.js | 21 +++++++++++++-------- packages/workbox/package.json | 1 + packages/workbox/templates/sw.template.js | 2 +- 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/packages/workbox/index.js b/packages/workbox/index.js index da9d0a9d..4f5c204f 100755 --- a/packages/workbox/index.js +++ b/packages/workbox/index.js @@ -2,6 +2,7 @@ const path = require('path') const swBuild = require('workbox-build') const { readFileSync, writeFileSync } = require('fs') const hashSum = require('hash-sum') +const escapeStringRegexp = require('escape-string-regexp') const debug = require('debug')('nuxt:pwa') const fixUrl = url => url.replace(/\/\//g, '/').replace(':/', '://') @@ -56,16 +57,16 @@ function getOptions (moduleOptions) { '': fixUrl(publicPath) }, runtimeCaching: [ - // Cache routes if offline - { - urlPattern: fixUrl(routerBase + '/**'), - handler: 'networkFirst' - }, - // Cache other _nuxt resources runtime + // Cache all _nuxt resources at runtime // They are hashed by webpack so are safe to loaded by cacheFirst handler { - urlPattern: fixUrl(publicPath + '/**'), + urlPattern: escapeStringRegexp(fixUrl(publicPath + '/')) + '.*', handler: 'cacheFirst' + }, + // Cache other routes if offline + { + urlPattern: escapeStringRegexp(fixUrl(routerBase + '/')) + '.*', + handler: 'networkFirst' } ] }, moduleOptions, this.options.workbox) @@ -84,7 +85,11 @@ function addTemplates (options) { fileName: 'sw.template.js', options: { importScripts: [options.wbDst].concat(options.importScripts || []), - runtimeCaching: options.runtimeCaching, + runtimeCaching: options.runtimeCaching.map(i => (Object.assign({}, i, { + urlPattern: i.urlPattern, + handler: i.handler || 'networkFirst', + method: i.method || 'GET' + }))), wbOptions: { cacheId: options.cacheId, clientsClaim: options.clientsClaim, diff --git a/packages/workbox/package.json b/packages/workbox/package.json index 0ebdc6ec..b34d1620 100755 --- a/packages/workbox/package.json +++ b/packages/workbox/package.json @@ -8,6 +8,7 @@ "access": "public" }, "dependencies": { + "escape-string-regexp": "^1.0.5", "workbox-build": "^2.1.1" } } diff --git a/packages/workbox/templates/sw.template.js b/packages/workbox/templates/sw.template.js index a387dbb6..c9bced95 100644 --- a/packages/workbox/templates/sw.template.js +++ b/packages/workbox/templates/sw.template.js @@ -5,5 +5,5 @@ const workboxSW = new self.WorkboxSW(<%= JSON.stringify(options.wbOptions, null, workboxSW.precache([]) <% options.runtimeCaching.forEach(r => { %> -workboxSW.router.registerRoute('<%= r.urlPattern %>', workboxSW.strategies.<%= r.handler %>({}), 'GET') +workboxSW.router.registerRoute(new RegExp('<%= r.urlPattern %>'), workboxSW.strategies.<%= r.handler %>({}), '<%= r.method %>') <% }) %>