UNPKG

2.6 kBJavaScriptView Raw
1const path = require('path')
2
3const defaults = require('./defaults')
4const { joinUrl, getRouteParams, startCase } = require('@nuxtjs/pwa-utils')
5
6const HMRRegex = '(?!.*(__webpack_hmr|hot-update))'
7
8function getOptions (moduleOptions) {
9 const options = Object.assign({}, defaults, moduleOptions, this.options.workbox)
10
11 // routerBase
12 if (!options.routerBase) {
13 options.routerBase = this.options.router.base
14 }
15
16 // publicPath
17 if (!options.publicPath) {
18 const { publicPath } = getRouteParams(this.options)
19 options.publicPath = publicPath
20 }
21
22 // swTemplate
23 if (!options.swTemplate) {
24 const disabled = this.options.dev && !options.dev
25 options.swTemplate = path.resolve(__dirname, `../templates/sw${disabled ? '.disable' : ''}.js`)
26 }
27
28 // swDest
29 if (!options.swDest) {
30 options.swDest = path.resolve(this.options.srcDir, this.options.dir.static || 'static', 'sw.js')
31 }
32
33 // swURL
34 if (!options.swURL) {
35 options.swURL = joinUrl(options.routerBase, 'sw.js')
36 }
37
38 // swScope
39 if (!options.swScope) {
40 options.swScope = options.routerBase
41 }
42
43 // Cache all _nuxt resources at runtime
44 if (!options.assetsURLPattern) {
45 options.assetsURLPattern = joinUrl(options.publicPath, HMRRegex)
46 }
47 if (options.cacheAssets) {
48 options.runtimeCaching.push({
49 urlPattern: options.assetsURLPattern,
50 handler: 'CacheFirst'
51 })
52 }
53
54 // Optionally cache other routes for offline
55 if (!options.pagesURLPattern) {
56 options.pagesURLPattern = joinUrl(options.routerBase, HMRRegex)
57 }
58 if (options.offline && !options.offlinePage) {
59 options.runtimeCaching.push({
60 urlPattern: options.pagesURLPattern,
61 handler: 'NetworkFirst'
62 })
63 }
64
65 // Add offlineAssets to precaching
66 if (options.offlineAssets.length) {
67 options.preCaching.unshift(...options.offlineAssets)
68 }
69
70 // Add offlinePage to precaching
71 if (options.offlinePage) {
72 options.preCaching.unshift(options.offlinePage)
73 }
74
75 // Normalize runtimeCaching
76 options.runtimeCaching = options.runtimeCaching.map(entry => ({
77 ...entry,
78 handler: startCase(entry.handler) || 'NetworkFirst',
79 method: entry.method || 'GET'
80 }))
81
82 // Workbox URL
83 if (!options.workboxURL) {
84 options.workboxURL = `https://cdn.jsdelivr.net/npm/workbox-cdn@${options.workboxVersion}/workbox/workbox-sw.js`
85 }
86
87 // Workbox Config
88 if (!options.config.debug) {
89 // Debug field is by default set to true for localhost domain which is not always ideal
90 options.config.debug = options.dev || this.options.dev
91 }
92
93 return options
94}
95
96module.exports = {
97 getOptions
98}