Skip to content

Commit

Permalink
refactor(workbox): avoid template as much as possible for sw.js
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Oct 1, 2020
1 parent dacf7ec commit 7dbaf70
Show file tree
Hide file tree
Showing 3 changed files with 98 additions and 78 deletions.
16 changes: 14 additions & 2 deletions lib/workbox/module.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const path = require('path')

const { getOptions } = require('./options')
const { readJSFiles } = require('./utils')
const { readJSFiles, pick } = require('./utils')

module.exports = function nuxtWorkbox (pwa) {
this.nuxt.hook('build:before', async () => {
Expand Down Expand Up @@ -32,7 +32,19 @@ module.exports = function nuxtWorkbox (pwa) {
src: options.swTemplate,
fileName: options.swDest,
options: {
...options,
swOptions: pick(options, [
'workboxURL',
'importScripts',
'config',
'cacheNames',
'clientsClaim',
'skipWaiting',
'cleanupOutdatedCaches',
'offlineAnalytics',
'preCaching',
'runtimeCaching',
'offlinePage'
]),
routingExtensions: await readJSFiles.call(this, options.routingExtensions),
cachingExtensions: await readJSFiles.call(this, options.cachingExtensions),
workboxExtensions: await readJSFiles.call(this, options.workboxExtensions)
Expand Down
149 changes: 74 additions & 75 deletions lib/workbox/templates/sw.js
Original file line number Diff line number Diff line change
@@ -1,90 +1,89 @@
importScripts(<%= [options.workboxURL, ...options.importScripts].map((i) => `'${i}'`).join(', ') %>)
const options = <%= JSON.stringify(options.swOptions) %>

// --------------------------------------------------
// Configure
// --------------------------------------------------
importScripts(...[options.workboxURL, ...options.importScripts])

<% if (options.config) {%>
// Set workbox config
workbox.setConfig(<%= JSON.stringify(options.config, null, 2) %>)
<% } %>
initWorkbox(workbox, options)
workboxExtensions(workbox, options)
precacheAssets(workbox, options)
cachingExtensions(workbox, options)
runtimeCaching(workbox, options)
offlinePage(workbox, options)
routingExtensions(workbox, options)

<% if (options.cacheNames) {%>
// Set workbox cache names
workbox.core.setCacheNameDetails(<%= JSON.stringify(options.cacheNames, null, 2) %>)
<% } %>

<% if (options.clientsClaim) { %>
// Start controlling any existing clients as soon as it activates
workbox.core.clientsClaim()
<% } %>

<% if (options.skipWaiting) { %>
// Skip over the SW waiting lifecycle stage
workbox.core.skipWaiting()
<% } %>

<% if (options.cleanupOutdatedCaches) { %>
workbox.precaching.cleanupOutdatedCaches()
<% } %>

<% if (options.offlineAnalytics) { %>
// Enable offline Google Analytics tracking
workbox.googleAnalytics.initialize()
<% } %>

<% if (options.workboxExtensions) { %>
// -- Start of workboxExtensions --
<%= options.workboxExtensions %>// -- End of workboxExtensions --
<% } %>

// --------------------------------------------------
// Precaches
// --------------------------------------------------

// Precache assets
<% if (options.preCaching.length) { %>
workbox.precaching.precacheAndRoute(<%= JSON.stringify(options.preCaching, null, 2) %>, <%= JSON.stringify(options.cacheOptions, null, 2) %>)
<% } %>
function getProp(obj, prop) {
return prop.split('.').reduce((p, c) => p[c], obj)
}

<% if (options.cachingExtensions) { %>
// -- Start of cachingExtensions --
<%= options.cachingExtensions %>// -- End of cachingExtensions --
<% } %>
function initWorkbox(workbox, options) {
if (options.config) {
// Set workbox config
workbox.setConfig(options.config)
}

if (options.cacheNames) {
// Set workbox cache names
workbox.core.setCacheNameDetails(options.cacheNames)
}

if (options.clientsClaim) {
// Start controlling any existing clients as soon as it activates
workbox.core.clientsClaim()
}

if (options.skipWaiting) {
workbox.core.skipWaiting()
}

if (options.cleanupOutdatedCaches) {
workbox.precaching.cleanupOutdatedCaches()
}

if (options.offlineAnalytics) {
// Enable offline Google Analytics tracking
workbox.googleAnalytics.initialize()
}
}

// --------------------------------------------------
// Runtime Caching
// --------------------------------------------------
function precacheAssets(workbox, options) {
if (options.preCaching.length) {
workbox.precaching.precacheAndRoute(options.preCaching, options.cacheOptions)
}
}

// Register route handlers for runtimeCaching
function runtimeCaching(workbox, options) {
for (const entry of options.runtimeCaching) {
const urlPattern = new RegExp(entry.urlPattern)
const method = entry.method || 'GET'

const runtimeCaching = <%= JSON.stringify(options.runtimeCaching, null, 2) %>
const plugins = (entry.strategyPlugins || [])
.map(p => new (getProp(workbox, p.use))(...p.config))

const getProp = (obj, prop) => prop.split('.').reduce((p, c) => p[c], obj)
const strategyOptions = { ...entry.strategyOptions, plugins }

for (const cache of runtimeCaching) {
const urlPattern = new RegExp(cache.urlPattern)
const method = cache.method || 'GET'
const strategy = new workbox.strategies[entry.handler](strategyOptions)

const plugins = (cache.strategyPlugins || [])
.map(p => new (getProp(workbox, p.use))(...p.config))
workbox.routing.registerRoute(urlPattern, strategy, method)
}
}

const strategyOptions = { ...cache.strategyOptions, plugins }
const strategy = new workbox.strategies[cache.handler](strategyOptions)
function offlinePage(workbox, options) {
// Register router handler for offlinePage
workbox.routing.registerRoute(new RegExp(options.pagesURLPattern), ({ request, event }) => {
const strategy = new workbox.strategies[options.offlineStrategy]
return strategy
.handle({ request, event })
.catch(() => caches.match(options.offlinePage))
})
}

console.log('registerRoute', { urlPattern, strategyOptions, strategy, method })
function workboxExtensions(workbox, options) {
<%= options.workboxExtensions %>
}

workbox.routing.registerRoute(urlPattern, strategy, method)
function cachingExtensions(workbox, options) {
<%= options.cachingExtensions %>
}

<% if (options.offlinePage) { %>
// Register router handler for offlinePage
workbox.routing.registerRoute(new RegExp('<%= options.pagesURLPattern %>'), ({request,event}) => {
return new workbox.strategies.<%= options.offlineStrategy %>().handle({request,event})
.catch(() => caches.match('<%= options.offlinePage %>'))
})<% } %>

<% if (options.routingExtensions) { %>
// -- Start of routingExtensions --
<%= options.routingExtensions %>// -- End of routingExtensions --
<% } %>
function routingExtensions(workbox, options) {
<%= options.routingExtensions %>
}
11 changes: 10 additions & 1 deletion lib/workbox/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@ async function readJSFiles (files) {
return contents.join('\n\n')
}

function pick (obj, props) {
const newObj = {}
props.forEach((prop) => {
newObj[prop] = obj[prop]
})
return newObj
}

module.exports = {
readJSFiles
readJSFiles,
pick
}

0 comments on commit 7dbaf70

Please sign in to comment.