Skip to content

Commit 7c8644c

Browse files
author
Pooya Parsa
committedNov 16, 2017
feat(workbox): importScripts option
1 parent e1363db commit 7c8644c

File tree

5 files changed

+72
-56
lines changed

5 files changed

+72
-56
lines changed
 

Diff for: ‎README.md

+5-2
Original file line numberDiff line numberDiff line change
@@ -96,8 +96,11 @@ workbox: {
9696

9797
### Options
9898

99-
**dev**: Use dev build for workbox service worker lib.
100-
**swURL**: If for any reason you need to register another service worker (OneSignal, etc) you can use this option.
99+
**dev** - Use dev build for workbox service worker lib.
100+
101+
**swURL** - If for any reason you need to register another service worker (OneSignal, etc) you can use this option.
102+
103+
**importScripts** (Array) - Additional scripts to be imported in service worker script. (Relative to `/`. Can be placed in `assets/` directory)
101104

102105
For list of all available options see [this table](https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-build#abstract-types)
103106

Diff for: ‎packages/workbox/index.js

+50-47
Original file line numberDiff line numberDiff line change
@@ -12,19 +12,16 @@ const isUrl = url => url.indexOf('http') === 0 || url.indexOf('//') === 0
1212
// =============================================
1313

1414
module.exports = function nuxtWorkbox (moduleOptions) {
15-
const options = Object.assign({}, moduleOptions, this.options.workbox)
16-
const ctx = { options }
17-
1815
if (this.options.dev) {
1916
return
2017
}
2118

2219
const hook = builder => {
2320
debug('Adding workbox')
24-
getRouterBase.call(this, ctx)
25-
workboxInject.call(this, ctx)
26-
emitAssets.call(this, ctx)
27-
addTemplates.call(this, ctx)
21+
const options = getOptions.call(this, moduleOptions)
22+
workboxInject.call(this, options)
23+
emitAssets.call(this, options)
24+
addTemplates.call(this, options)
2825
}
2926

3027
this.nuxt.hook ? this.nuxt.hook('build:before', hook) : this.nuxt.plugin('build', hook)
@@ -34,7 +31,8 @@ module.exports = function nuxtWorkbox (moduleOptions) {
3431
// getRouterBase
3532
// =============================================
3633

37-
function getRouterBase (ctx) {
34+
function getOptions (moduleOptions) {
35+
// Router Base
3836
const routerBase = this.options.router.base
3937
let publicPath = fixUrl(`${routerBase}/${this.options.build.publicPath}`)
4038
if (isUrl(this.options.build.publicPath)) { // CDN
@@ -44,34 +42,66 @@ function getRouterBase (ctx) {
4442
}
4543
}
4644

47-
ctx.routerBase = routerBase
48-
ctx.publicPath = publicPath
45+
const options = Object.assign({
46+
routerBase,
47+
publicPath,
48+
swSrc: path.resolve(this.options.buildDir, 'sw.template.js'),
49+
swDest: path.resolve(this.options.srcDir, 'static', 'sw.js'),
50+
directoryIndex: '/',
51+
cacheId: process.env.npm_package_name + '_' + process.env.npm_package_version,
52+
clientsClaim: true,
53+
globPatterns: ['**/*.{js,css}'],
54+
globDirectory: path.resolve(this.options.buildDir, 'dist'),
55+
modifyUrlPrefix: {
56+
'': fixUrl(publicPath)
57+
},
58+
runtimeCaching: [
59+
// Cache routes if offline
60+
{
61+
urlPattern: fixUrl(routerBase + '/**'),
62+
handler: 'networkFirst'
63+
},
64+
// Cache other _nuxt resources runtime
65+
// They are hashed by webpack so are safe to loaded by cacheFirst handler
66+
{
67+
urlPattern: fixUrl(publicPath + '/**'),
68+
handler: 'cacheFirst'
69+
}
70+
]
71+
}, moduleOptions, this.options.workbox)
72+
73+
return options
4974
}
5075

5176
// =============================================
5277
// addTemplates
5378
// =============================================
5479

55-
function addTemplates (ctx) {
80+
function addTemplates (options) {
5681
// Add sw.template.js
5782
this.addTemplate({
5883
src: path.resolve(__dirname, 'templates/sw.template.js'),
5984
fileName: 'sw.template.js',
6085
options: {
61-
importPath: ctx.wbDst,
62-
wb: ctx.workboxOptions
86+
importScripts: [options.wbDst].concat(options.importScripts || []),
87+
runtimeCaching: options.runtimeCaching,
88+
wbOptions: {
89+
cacheId: options.cacheId,
90+
clientsClaim: options.clientsClaim,
91+
directoryIndex: options.directoryIndex
92+
}
6393
}
6494
})
6595

6696
// Add sw.plugin.js
67-
const swURL = `${ctx.routerBase}/${ctx.options.swURL || 'sw.js'}`
97+
const swURL = `${options.routerBase}/${options.swURL || 'sw.js'}`
6898
this.addPlugin({
6999
src: path.resolve(__dirname, 'templates/sw.plugin.js'),
70100
ssr: false,
71101
fileName: 'sw.plugin.js',
72102
options: {
73103
swURL: fixUrl(swURL),
74-
swScope: fixUrl(`${ctx.routerBase}/`)
104+
swScope: fixUrl(`${options.routerBase}/`)
75105
}
76106
})
77107
}
@@ -80,7 +110,7 @@ function addTemplates (ctx) {
80110
// emitAssets
81111
// =============================================
82112

83-
function emitAssets (ctx) {
113+
function emitAssets (options) {
84114
const assets = []
85115
const emitAsset = (path, name, ext = 'js') => {
86116
const source = readFileSync(path)
@@ -107,46 +137,19 @@ function emitAssets (ctx) {
107137

108138
// workbox.js
109139
let wbPath = require.resolve('workbox-sw')
110-
if (ctx.options.dev) {
140+
if (options.dev) {
111141
wbPath = wbPath.replace(/prod/g, 'dev')
112142
}
113-
ctx.wbDst = fixUrl(ctx.publicPath + '/' + emitAsset(wbPath, 'workbox' + (ctx.options.dev ? '.dev' : '')))
143+
options.wbDst = fixUrl(options.publicPath + '/' + emitAsset(wbPath, 'workbox' + (options.dev ? '.dev' : '')))
114144
}
115145

116146
// =============================================
117147
// workboxInject
118148
// =============================================
119149

120-
function workboxInject (ctx) {
121-
// https://workboxjs.org/reference-docs/latest/module-workbox-build.html#.generateSW
122-
ctx.workboxOptions = Object.assign({
123-
swSrc: path.resolve(this.options.buildDir, 'sw.template.js'),
124-
swDest: path.resolve(this.options.srcDir, 'static', 'sw.js'),
125-
directoryIndex: '/',
126-
cacheId: process.env.npm_package_name + '_' + process.env.npm_package_version,
127-
clientsClaim: true,
128-
globPatterns: ['**/*.{js,css}'],
129-
globDirectory: path.resolve(this.options.buildDir, 'dist'),
130-
modifyUrlPrefix: {
131-
'': fixUrl(ctx.publicPath)
132-
},
133-
runtimeCaching: [
134-
// Cache routes if offline
135-
{
136-
urlPattern: fixUrl(ctx.routerBase + '/**'),
137-
handler: 'networkFirst'
138-
},
139-
// Cache other _nuxt resources runtime
140-
// They are hashed by webpack so are safe to loaded by cacheFirst handler
141-
{
142-
urlPattern: fixUrl(ctx.publicPath + '/**'),
143-
handler: 'cacheFirst'
144-
}
145-
]
146-
}, ctx.options)
147-
150+
function workboxInject (options) {
148151
const hook = () => {
149-
const opts = Object.assign({}, ctx.workboxOptions)
152+
const opts = Object.assign({}, options)
150153
delete opts.runtimeCaching
151154
return swBuild.injectManifest(opts)
152155
}

Diff for: ‎packages/workbox/templates/sw.template.js

+3-7
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,9 @@
1-
importScripts('<%= options.importPath %>')
1+
importScripts(<%= options.importScripts.map(i => `'${i}'`).join(', ') %>)
22

3-
const workboxSW = new self.WorkboxSW({
4-
cacheId: '<%= options.wb.cacheId %>',
5-
clientsClaim: <%= options.wb.clientsClaim %>,
6-
directoryIndex: '<%= options.wb.directoryIndex %>'
7-
})
3+
const workboxSW = new self.WorkboxSW(<%= JSON.stringify(options.wbOptions, null, 2) %>)
84

95
workboxSW.precache([])
106

11-
<% options.wb.runtimeCaching.forEach(r => { %>
7+
<% options.runtimeCaching.forEach(r => { %>
128
workboxSW.router.registerRoute('<%= r.urlPattern %>', workboxSW.strategies.<%= r.handler %>({}), 'GET')
139
<% }) %>

Diff for: ‎test/fixture/nuxt.config.js

+5
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,10 @@ module.exports = {
1717
manifest: {
1818
name: 'Test Project Name',
1919
description: 'Test Project Description'
20+
},
21+
workbox: {
22+
importScripts: [
23+
'custom-sw.js'
24+
]
2025
}
2126
}

Diff for: ‎test/fixture/static/custom-sw.js

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
console.log('Custom service worker!')
2+
3+
self.addEventListener('install', function (e) {
4+
console.log('Install event:', e)
5+
})
6+
7+
self.addEventListener('activate', function (e) {
8+
console.log('Activate event:', e)
9+
})

0 commit comments

Comments
 (0)
Please sign in to comment.