generate-sw.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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 {
  9. RawSource
  10. } = require('webpack-sources');
  11. const bundle = require('workbox-build/build/lib/bundle');
  12. const populateSWTemplate = require('workbox-build/build/lib/populate-sw-template');
  13. const validate = require('workbox-build/build/lib/validate-options');
  14. const webpackGenerateSWSchema = require('workbox-build/build/options/schema/webpack-generate-sw');
  15. const getScriptFilesForChunks = require('./lib/get-script-files-for-chunks');
  16. const getManifestEntriesFromCompilation = require('./lib/get-manifest-entries-from-compilation');
  17. const relativeToOutputPath = require('./lib/relative-to-output-path'); // Used to keep track of swDest files written by *any* instance of this plugin.
  18. // See https://github.com/GoogleChrome/workbox/issues/2181
  19. const _generatedAssetNames = new Set();
  20. /**
  21. * This class supports creating a new, ready-to-use service worker file as
  22. * part of the webpack compilation process.
  23. *
  24. * Use an instance of `GenerateSW` in the
  25. * [`plugins` array](https://webpack.js.org/concepts/plugins/#usage) of a
  26. * webpack config.
  27. *
  28. * @memberof module:workbox-webpack-plugin
  29. */
  30. class GenerateSW {
  31. // eslint-disable-next-line jsdoc/newline-after-description
  32. /**
  33. * Creates an instance of GenerateSW.
  34. *
  35. * @param {Object} config The configuration to use.
  36. *
  37. * @param {Array<module:workbox-build.ManifestEntry>} [config.additionalManifestEntries]
  38. * A list of entries to be precached, in addition to any entries that are
  39. * generated as part of the build configuration.
  40. *
  41. * @param {Array<string>} [config.babelPresetEnvTargets=['chrome >= 56']]
  42. * The [targets](https://babeljs.io/docs/en/babel-preset-env#targets) to pass to
  43. * `babel-preset-env` when transpiling the service worker bundle.
  44. *
  45. * @param {string} [config.cacheId] An optional ID to be prepended to cache
  46. * names. This is primarily useful for local development where multiple sites
  47. * may be served from the same `http://localhost:port` origin.
  48. *
  49. * @param {boolean} [config.cleanupOutdatedCaches=false] Whether or not Workbox
  50. * should attempt to identify an delete any precaches created by older,
  51. * incompatible versions.
  52. *
  53. * @param {boolean} [config.clientsClaim=false] Whether or not the service
  54. * worker should [start controlling](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#clientsclaim)
  55. * any existing clients as soon as it activates.
  56. *
  57. * @param {Array<string>} [config.chunks] One or more chunk names whose corresponding
  58. * output files should be included in the precache manifest.
  59. *
  60. * @param {string} [config.directoryIndex='index.html'] If a navigation request
  61. * for a URL ending in `/` fails to match a precached URL, this value will be
  62. * appended to the URL and that will be checked for a precache match. This
  63. * should be set to what your web server is using for its directory index.
  64. *
  65. * @param {RegExp} [config.dontCacheBustURLsMatching] Assets that match this will be
  66. * assumed to be uniquely versioned via their URL, and exempted from the normal
  67. * HTTP cache-busting that's done when populating the precache. While not
  68. * required, it's recommended that if your existing build process already
  69. * inserts a `[hash]` value into each filename, you provide a RegExp that will
  70. * detect that, as it will reduce the bandwidth consumed when precaching.
  71. *
  72. * @param {Array<string|RegExp|Function>} [config.exclude=[/\.map$/, /^manifest.*\.js$]]
  73. * One or more specifiers used to exclude assets from the precache manifest.
  74. * This is interpreted following
  75. * [the same rules](https://webpack.js.org/configuration/module/#condition)
  76. * as `webpack`'s standard `exclude` option.
  77. *
  78. * @param {Array<string>} [config.excludeChunks] One or more chunk names whose
  79. * corresponding output files should be excluded from the precache manifest.
  80. *
  81. * @param {Array<RegExp>} [config.ignoreURLParametersMatching=[/^utm_/]]
  82. * Any search parameter names that match against one of the RegExp in this array
  83. * will be removed before looking for a precache match. This is useful if your
  84. * users might request URLs that contain, for example, URL parameters used to
  85. * track the source of the traffic.
  86. *
  87. * @param {Array<string>} [config.importScripts] A list of JavaScript files that
  88. * should be passed to [`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts)
  89. * inside the generated service worker file. This is useful when you want to
  90. * let Workbox create your top-level service worker file, but want to include
  91. * some additional code, such as a push event listener.
  92. *
  93. * @param {Array<string>} [config.importScriptsViaChunks] One or more names of
  94. * webpack chunks. The content of those chunks will be included in the
  95. * generated service worker, via a call to `importScripts()`.
  96. *
  97. * @param {Array<string|RegExp|Function>} [config.include]
  98. * One or more specifiers used to include assets in the precache manifest.
  99. * This is interpreted following
  100. * [the same rules](https://webpack.js.org/configuration/module/#condition)
  101. * as `webpack`'s standard `include` option.
  102. *
  103. * @param {boolean} [config.inlineWorkboxRuntime=false] Whether the runtime code
  104. * for the Workbox library should be included in the top-level service worker,
  105. * or split into a separate file that needs to be deployed alongside the service
  106. * worker. Keeping the runtime separate means that users will not have to
  107. * re-download the Workbox code each time your top-level service worker changes.
  108. *
  109. * @param {Array<module:workbox-build.ManifestTransform>} [config.manifestTransforms]
  110. * One or more functions which will be applied sequentially against the
  111. * generated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are
  112. * also specified, their corresponding transformations will be applied first.
  113. *
  114. * @param {number} [config.maximumFileSizeToCacheInBytes=2097152] This value can be
  115. * used to determine the maximum size of files that will be precached. This
  116. * prevents you from inadvertently precaching very large files that might have
  117. * accidentally matched one of your patterns.
  118. *
  119. * @param {string} [config.mode] If set to 'production', then an optimized service
  120. * worker bundle that excludes debugging info will be produced. If not explicitly
  121. * configured here, the `mode` value configured in the current `webpack` compiltion
  122. * will be used.
  123. *
  124. * @param {object<string, string>} [config.modifyURLPrefix] A mapping of prefixes
  125. * that, if present in an entry in the precache manifest, will be replaced with
  126. * the corresponding value. This can be used to, for example, remove or add a
  127. * path prefix from a manifest entry if your web hosting setup doesn't match
  128. * your local filesystem setup. As an alternative with more flexibility, you can
  129. * use the `manifestTransforms` option and provide a function that modifies the
  130. * entries in the manifest using whatever logic you provide.
  131. *
  132. * @param {string} [config.navigateFallback] If specified, all
  133. * [navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests)
  134. * for URLs that aren't precached will be fulfilled with the HTML at the URL
  135. * provided. You must pass in the URL of an HTML document that is listed in your
  136. * precache manifest. This is meant to be used in a Single Page App scenario, in
  137. * which you want all navigations to use common [App Shell HTML](https://developers.google.com/web/fundamentals/architecture/app-shell).
  138. *
  139. * @param {Array<RegExp>} [config.navigateFallbackDenylist] An optional array
  140. * of regular expressions that restricts which URLs the configured
  141. * `navigateFallback` behavior applies to. This is useful if only a subset of
  142. * your site's URLs should be treated as being part of a
  143. * [Single Page App](https://en.wikipedia.org/wiki/Single-page_application). If
  144. * both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are
  145. * configured, the denylist takes precedent.
  146. *
  147. * @param {Array<RegExp>} [config.navigateFallbackAllowlist] An optional array
  148. * of regular expressions that restricts which URLs the configured
  149. * `navigateFallback` behavior applies to. This is useful if only a subset of
  150. * your site's URLs should be treated as being part of a
  151. * [Single Page App](https://en.wikipedia.org/wiki/Single-page_application). If
  152. * both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are
  153. * configured, the denylist takes precedent.
  154. *
  155. * @param {boolean} [config.navigationPreload=false] Whether or not to enable
  156. * [navigation preload](https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload)
  157. * in the generated service worker. When set to true, you must also use
  158. * `runtimeCaching` to set up an appropriate response strategy that will match
  159. * navigation requests, and make use of the preloaded response.
  160. *
  161. * @param {boolean|Object} [config.offlineGoogleAnalytics=false] Controls
  162. * whether or not to include support for
  163. * [offline Google Analytics](https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics).
  164. * When `true`, the call to `workbox-google-analytics`'s `initialize()` will be
  165. * added to your generated service worker. When set to an `Object`, that object
  166. * will be passed in to the `initialize()` call, allowing you to customize the
  167. * behavior.
  168. *
  169. * @param {Array<module:workbox-build.RuntimeCachingEntry>} [config.runtimeCaching]
  170. *
  171. * @param {boolean} [config.skipWaiting=false] Whether to add an
  172. * unconditional call to [`skipWaiting()`]{@link module:workbox-core.skipWaiting}
  173. * to the generated service worker. If `false`, then a `message` listener will
  174. * be added instead, allowing you to conditionally call `skipWaiting()`.
  175. *
  176. * @param {boolean} [config.sourcemap=true] Whether to create a sourcemap
  177. * for the generated service worker files.
  178. *
  179. * @param {string} [config.swDest='service-worker.js'] The asset name of the
  180. * service worker file that will be created by this plugin.
  181. */
  182. constructor(config = {}) {
  183. this.config = config;
  184. this.alreadyCalled = false;
  185. }
  186. /**
  187. * @param {Object} [compiler] default compiler object passed from webpack
  188. *
  189. * @private
  190. */
  191. propagateWebpackConfig(compiler) {
  192. // Because this.config is listed last, properties that are already set
  193. // there take precedence over derived properties from the compiler.
  194. this.config = Object.assign({
  195. mode: compiler.options.mode,
  196. sourcemap: Boolean(compiler.options.devtool)
  197. }, this.config);
  198. }
  199. /**
  200. * @param {Object} [compiler] default compiler object passed from webpack
  201. *
  202. * @private
  203. */
  204. apply(compiler) {
  205. this.propagateWebpackConfig(compiler);
  206. compiler.hooks.emit.tapPromise(this.constructor.name, compilation => this.handleEmit(compilation).catch(error => compilation.errors.push(error)));
  207. }
  208. /**
  209. * @param {Object} compilation The webpack compilation.
  210. *
  211. * @private
  212. */
  213. async handleEmit(compilation) {
  214. // See https://github.com/GoogleChrome/workbox/issues/1790
  215. if (this.alreadyCalled) {
  216. compilation.warnings.push(`${this.constructor.name} has been called ` + `multiple times, perhaps due to running webpack in --watch mode. The ` + `precache manifest generated after the first call may be inaccurate! ` + `Please see https://github.com/GoogleChrome/workbox/issues/1790 for ` + `more information.`);
  217. } else {
  218. this.alreadyCalled = true;
  219. }
  220. let config;
  221. try {
  222. // emit might be called multiple times; instead of modifying this.config,
  223. // use a validated copy.
  224. // See https://github.com/GoogleChrome/workbox/issues/2158
  225. config = validate(this.config, webpackGenerateSWSchema);
  226. } catch (error) {
  227. throw new Error(`Please check your ${this.constructor.name} plugin ` + `configuration:\n${error.message}`);
  228. } // Ensure that we don't precache any of the assets generated by *any*
  229. // instance of this plugin.
  230. config.exclude.push(({
  231. asset
  232. }) => _generatedAssetNames.has(asset.name));
  233. if (config.importScriptsViaChunks) {
  234. // Anything loaded via importScripts() is implicitly cached by the service
  235. // worker, and should not be added to the precache manifest.
  236. config.excludeChunks = (config.excludeChunks || []).concat(config.importScriptsViaChunks);
  237. const scripts = getScriptFilesForChunks(compilation, config.importScriptsViaChunks);
  238. config.importScripts = (config.importScripts || []).concat(scripts);
  239. }
  240. config.manifestEntries = await getManifestEntriesFromCompilation(compilation, config);
  241. const unbundledCode = populateSWTemplate(config);
  242. const files = await bundle({
  243. babelPresetEnvTargets: config.babelPresetEnvTargets,
  244. inlineWorkboxRuntime: config.inlineWorkboxRuntime,
  245. mode: config.mode,
  246. sourcemap: config.sourcemap,
  247. swDest: relativeToOutputPath(compilation, config.swDest),
  248. unbundledCode
  249. });
  250. for (const file of files) {
  251. compilation.assets[file.name] = new RawSource(file.contents);
  252. _generatedAssetNames.add(file.name);
  253. }
  254. }
  255. }
  256. module.exports = GenerateSW;