generate-sw.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. "use strict";
  2. /*
  3. Copyright 2018 Google LLC
  4. Use of this source code is governed by an MIT-style
  5. license that can be found in the LICENSE file or at
  6. https://opensource.org/licenses/MIT.
  7. */
  8. const upath = require('upath');
  9. const generateSWSchema = require('./options/schema/generate-sw');
  10. const getFileManifestEntries = require('./lib/get-file-manifest-entries');
  11. const rebasePath = require('./lib/rebase-path');
  12. const validate = require('./lib/validate-options');
  13. const writeServiceWorkerUsingDefaultTemplate = require('./lib/write-sw-using-default-template'); // eslint-disable-next-line jsdoc/newline-after-description
  14. /**
  15. * This method creates a list of URLs to precache, referred to as a "precache
  16. * manifest", based on the options you provide.
  17. *
  18. * It also takes in additional options that configures the service worker's
  19. * behavior, like any `runtimeCaching` rules it should use.
  20. *
  21. * Based on the precache manifest and the additional configuration, it writes
  22. * a ready-to-use service worker file to disk at `swDest`.
  23. *
  24. * @param {Object} config The configuration to use.
  25. *
  26. * @param {string} config.globDirectory The local directory you wish to match
  27. * `globPatterns` against. The path is relative to the current directory.
  28. *
  29. * @param {string} config.swDest The path and filename of the service worker file
  30. * that will be created by the build process, relative to the current working
  31. * directory. It must end in '.js'.
  32. *
  33. * @param {Array<module:workbox-build.ManifestEntry>} [config.additionalManifestEntries]
  34. * A list of entries to be precached, in addition to any entries that are
  35. * generated as part of the build configuration.
  36. *
  37. * @param {Array<string>} [config.babelPresetEnvTargets=['chrome >= 56']]
  38. * The [targets](https://babeljs.io/docs/en/babel-preset-env#targets) to pass to
  39. * `babel-preset-env` when transpiling the service worker bundle.
  40. *
  41. * @param {string} [config.cacheId] An optional ID to be prepended to cache
  42. * names. This is primarily useful for local development where multiple sites
  43. * may be served from the same `http://localhost:port` origin.
  44. *
  45. * @param {boolean} [config.cleanupOutdatedCaches=false] Whether or not Workbox
  46. * should attempt to identify an delete any precaches created by older,
  47. * incompatible versions.
  48. *
  49. * @param {boolean} [config.clientsClaim=false] Whether or not the service
  50. * worker should [start controlling](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#clientsclaim)
  51. * any existing clients as soon as it activates.
  52. *
  53. * @param {string} [config.directoryIndex='index.html'] If a navigation request
  54. * for a URL ending in `/` fails to match a precached URL, this value will be
  55. * appended to the URL and that will be checked for a precache match. This
  56. * should be set to what your web server is using for its directory index.
  57. *
  58. * @param {RegExp} [config.dontCacheBustURLsMatching] Assets that match this will be
  59. * assumed to be uniquely versioned via their URL, and exempted from the normal
  60. * HTTP cache-busting that's done when populating the precache. While not
  61. * required, it's recommended that if your existing build process already
  62. * inserts a `[hash]` value into each filename, you provide a RegExp that will
  63. * detect that, as it will reduce the bandwidth consumed when precaching.
  64. *
  65. * @param {boolean} [config.globFollow=true] Determines whether or not symlinks
  66. * are followed when generating the precache manifest. For more information, see
  67. * the definition of `follow` in the `glob`
  68. * [documentation](https://github.com/isaacs/node-glob#options).
  69. *
  70. * @param {Array<string>} [config.globIgnores=['node_modules/**']]
  71. * A set of patterns matching files to always exclude when generating the
  72. * precache manifest. For more information, see the definition of `ignore` in the `glob`
  73. * [documentation](https://github.com/isaacs/node-glob#options).
  74. *
  75. * @param {Array<string>} [config.globPatterns=['**.{js,css,html}']]
  76. * Files matching any of these patterns will be included in the precache
  77. * manifest. For more information, see the
  78. * [`glob` primer](https://github.com/isaacs/node-glob#glob-primer).
  79. *
  80. * @param {boolean} [config.globStrict=true] If true, an error reading a directory when
  81. * generating a precache manifest will cause the build to fail. If false, the
  82. * problematic directory will be skipped. For more information, see the
  83. * definition of `strict` in the `glob`
  84. * [documentation](https://github.com/isaacs/node-glob#options).
  85. *
  86. * @param {Array<RegExp>} [config.ignoreURLParametersMatching=[/^utm_/]]
  87. * Any search parameter names that match against one of the RegExp in this array
  88. * will be removed before looking for a precache match. This is useful if your
  89. * users might request URLs that contain, for example, URL parameters used to
  90. * track the source of the traffic.
  91. *
  92. * @param {Array<string>} [config.importScripts] A list of JavaScript files that
  93. * should be passed to [`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts)
  94. * inside the generated service worker file. This is useful when you want to
  95. * let Workbox create your top-level service worker file, but want to include
  96. * some additional code, such as a push event listener.
  97. *
  98. * @param {boolean} [config.inlineWorkboxRuntime=false] Whether the runtime code
  99. * for the Workbox library should be included in the top-level service worker,
  100. * or split into a separate file that needs to be deployed alongside the service
  101. * worker. Keeping the runtime separate means that users will not have to
  102. * re-download the Workbox code each time your top-level service worker changes.
  103. *
  104. * @param {Array<module:workbox-build.ManifestTransform>} [config.manifestTransforms] One or more
  105. * functions which will be applied sequentially against the generated manifest.
  106. * If `modifyURLPrefix` or `dontCacheBustURLsMatching` are also specified, their
  107. * corresponding transformations will be applied first.
  108. *
  109. * @param {number} [config.maximumFileSizeToCacheInBytes=2097152] This value can be
  110. * used to determine the maximum size of files that will be precached. This
  111. * prevents you from inadvertently precaching very large files that might have
  112. * accidentally matched one of your patterns.
  113. *
  114. * @param {string} [config.mode='production'] If set to 'production', then an
  115. * optimized service worker bundle that excludes debugging info will be
  116. * produced. If not explicitly configured here, the `process.env.NODE_ENV` value
  117. * will be used, and failing that, it will fall back to `'production'`.
  118. *
  119. * @param {object<string, string>} [config.modifyURLPrefix] A mapping of prefixes
  120. * that, if present in an entry in the precache manifest, will be replaced with
  121. * the corresponding value. This can be used to, for example, remove or add a
  122. * path prefix from a manifest entry if your web hosting setup doesn't match
  123. * your local filesystem setup. As an alternative with more flexibility, you can
  124. * use the `manifestTransforms` option and provide a function that modifies the
  125. * entries in the manifest using whatever logic you provide.
  126. *
  127. * @param {string} [config.navigateFallback] If specified, all
  128. * [navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests)
  129. * for URLs that aren't precached will be fulfilled with the HTML at the URL
  130. * provided. You must pass in the URL of an HTML document that is listed in your
  131. * precache manifest. This is meant to be used in a Single Page App scenario, in
  132. * which you want all navigations to use common [App Shell HTML](https://developers.google.com/web/fundamentals/architecture/app-shell).
  133. *
  134. * @param {Array<RegExp>} [config.navigateFallbackDenylist] An optional array
  135. * of regular expressions that restricts which URLs the configured
  136. * `navigateFallback` behavior applies to. This is useful if only a subset of
  137. * your site's URLs should be treated as being part of a
  138. * [Single Page App](https://en.wikipedia.org/wiki/Single-page_application). If
  139. * both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are
  140. * configured, the denylist takes precedent.
  141. *
  142. * @param {Array<RegExp>} [config.navigateFallbackAllowlist] An optional array
  143. * of regular expressions that restricts which URLs the configured
  144. * `navigateFallback` behavior applies to. This is useful if only a subset of
  145. * your site's URLs should be treated as being part of a
  146. * [Single Page App](https://en.wikipedia.org/wiki/Single-page_application). If
  147. * both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are
  148. * configured, the denylist takes precedent.
  149. *
  150. * @param {boolean} [config.navigationPreload=false] Whether or not to enable
  151. * [navigation preload](https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload)
  152. * in the generated service worker. When set to true, you must also use
  153. * `runtimeCaching` to set up an appropriate response strategy that will match
  154. * navigation requests, and make use of the preloaded response.
  155. *
  156. * @param {boolean|Object} [config.offlineGoogleAnalytics=false] Controls
  157. * whether or not to include support for
  158. * [offline Google Analytics](https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics).
  159. * When `true`, the call to `workbox-google-analytics`'s `initialize()` will be
  160. * added to your generated service worker. When set to an `Object`, that object
  161. * will be passed in to the `initialize()` call, allowing you to customize the
  162. * behavior.
  163. *
  164. * @param {Array<RuntimeCachingEntry>} [config.runtimeCaching]
  165. *
  166. * @param {boolean} [config.skipWaiting=false] Whether to add an
  167. * unconditional call to [`skipWaiting()`]{@link module:workbox-core.skipWaiting}
  168. * to the generated service worker. If `false`, then a `message` listener will
  169. * be added instead, allowing you to conditionally call `skipWaiting()`.
  170. *
  171. * @param {boolean} [config.sourcemap=true] Whether to create a sourcemap
  172. * for the generated service worker files.
  173. *
  174. * @param {Object} [config.templatedURLs] If a URL is rendered based on some
  175. * server-side logic, its contents may depend on multiple files or on some other
  176. * unique string value. The keys in this object are server-rendered URLs. If the
  177. * values are an array of strings, they will be interpreted as `glob` patterns,
  178. * and the contents of any files matching the patterns will be used to uniquely
  179. * version the URL. If used with a single string, it will be interpreted as
  180. * unique versioning information that you've generated for a given URL.
  181. *
  182. * @return {Promise<{count: number, filePaths: Array<string>, size: number, warnings: Array<string>}>}
  183. * A promise that resolves once the service worker and related files
  184. * (indicated by `filePaths`) has been written to `swDest`. The `size` property
  185. * contains the aggregate size of all the precached entries, in bytes, and the
  186. * `count` property contains the total number of precached entries. Any
  187. * non-fatal warning messages will be returned via `warnings`.
  188. *
  189. * @memberof module:workbox-build
  190. */
  191. async function generateSW(config) {
  192. const options = validate(config, generateSWSchema);
  193. if (options.globDirectory) {
  194. // Make sure we leave swDest out of the precache manifest.
  195. options.globIgnores.push(rebasePath({
  196. baseDirectory: options.globDirectory,
  197. file: options.swDest
  198. })); // If we create an extra external runtime file, ignore that, too.
  199. // See https://rollupjs.org/guide/en/#outputchunkfilenames for naming.
  200. if (!options.inlineWorkboxRuntime) {
  201. const swDestDir = upath.dirname(options.swDest);
  202. const workboxRuntimeFile = upath.join(swDestDir, 'workbox-*.js');
  203. options.globIgnores.push(rebasePath({
  204. baseDirectory: options.globDirectory,
  205. file: workboxRuntimeFile
  206. }));
  207. }
  208. }
  209. const {
  210. count,
  211. size,
  212. manifestEntries,
  213. warnings
  214. } = await getFileManifestEntries(options);
  215. const filePaths = await writeServiceWorkerUsingDefaultTemplate(Object.assign({
  216. manifestEntries
  217. }, options));
  218. return {
  219. count,
  220. filePaths,
  221. size,
  222. warnings
  223. };
  224. }
  225. module.exports = generateSW;