generate-sw.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. var __importDefault = (this && this.__importDefault) || function (mod) {
  9. return (mod && mod.__esModule) ? mod : { "default": mod };
  10. };
  11. Object.defineProperty(exports, "__esModule", { value: true });
  12. exports.GenerateSW = void 0;
  13. const validate_options_1 = require("workbox-build/build/lib/validate-options");
  14. const bundle_1 = require("workbox-build/build/lib/bundle");
  15. const populate_sw_template_1 = require("workbox-build/build/lib/populate-sw-template");
  16. const pretty_bytes_1 = __importDefault(require("pretty-bytes"));
  17. const webpack_1 = __importDefault(require("webpack"));
  18. const get_script_files_for_chunks_1 = require("./lib/get-script-files-for-chunks");
  19. const get_manifest_entries_from_compilation_1 = require("./lib/get-manifest-entries-from-compilation");
  20. const relative_to_output_path_1 = require("./lib/relative-to-output-path");
  21. // webpack v4/v5 compatibility:
  22. // https://github.com/webpack/webpack/issues/11425#issuecomment-686607633
  23. const { RawSource } = webpack_1.default.sources || require('webpack-sources');
  24. // Used to keep track of swDest files written by *any* instance of this plugin.
  25. // See https://github.com/GoogleChrome/workbox/issues/2181
  26. const _generatedAssetNames = new Set();
  27. /**
  28. * This class supports creating a new, ready-to-use service worker file as
  29. * part of the webpack compilation process.
  30. *
  31. * Use an instance of `GenerateSW` in the
  32. * [`plugins` array](https://webpack.js.org/concepts/plugins/#usage) of a
  33. * webpack config.
  34. *
  35. * ```
  36. * // The following lists some common options; see the rest of the documentation
  37. * // for the full set of options and defaults.
  38. * new GenerateSW({
  39. * exclude: [/.../, '...'],
  40. * maximumFileSizeToCacheInBytes: ...,
  41. * navigateFallback: '...',
  42. * runtimeCaching: [{
  43. * // Routing via a matchCallback function:
  44. * urlPattern: ({request, url}) => ...,
  45. * handler: '...',
  46. * options: {
  47. * cacheName: '...',
  48. * expiration: {
  49. * maxEntries: ...,
  50. * },
  51. * },
  52. * }, {
  53. * // Routing via a RegExp:
  54. * urlPattern: new RegExp('...'),
  55. * handler: '...',
  56. * options: {
  57. * cacheName: '...',
  58. * plugins: [..., ...],
  59. * },
  60. * }],
  61. * skipWaiting: ...,
  62. * });
  63. * ```
  64. *
  65. * @memberof module:workbox-webpack-plugin
  66. */
  67. class GenerateSW {
  68. /**
  69. * Creates an instance of GenerateSW.
  70. */
  71. constructor(config = {}) {
  72. this.config = config;
  73. this.alreadyCalled = false;
  74. }
  75. /**
  76. * @param {Object} [compiler] default compiler object passed from webpack
  77. *
  78. * @private
  79. */
  80. propagateWebpackConfig(compiler) {
  81. // Because this.config is listed last, properties that are already set
  82. // there take precedence over derived properties from the compiler.
  83. this.config = Object.assign({
  84. mode: compiler.options.mode,
  85. sourcemap: Boolean(compiler.options.devtool),
  86. }, this.config);
  87. }
  88. /**
  89. * @param {Object} [compiler] default compiler object passed from webpack
  90. *
  91. * @private
  92. */
  93. apply(compiler) {
  94. this.propagateWebpackConfig(compiler);
  95. // webpack v4/v5 compatibility:
  96. // https://github.com/webpack/webpack/issues/11425#issuecomment-690387207
  97. if (webpack_1.default.version.startsWith('4.')) {
  98. compiler.hooks.emit.tapPromise(this.constructor.name, (compilation) => this.addAssets(compilation).catch((error) => {
  99. compilation.errors.push(error);
  100. }));
  101. }
  102. else {
  103. const { PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER } = webpack_1.default.Compilation;
  104. // Specifically hook into thisCompilation, as per
  105. // https://github.com/webpack/webpack/issues/11425#issuecomment-690547848
  106. compiler.hooks.thisCompilation.tap(this.constructor.name, (compilation) => {
  107. compilation.hooks.processAssets.tapPromise({
  108. name: this.constructor.name,
  109. // TODO(jeffposnick): This may need to change eventually.
  110. // See https://github.com/webpack/webpack/issues/11822#issuecomment-726184972
  111. stage: PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER - 10,
  112. }, () => this.addAssets(compilation).catch((error) => {
  113. compilation.errors.push(error);
  114. }));
  115. });
  116. }
  117. }
  118. /**
  119. * @param {Object} compilation The webpack compilation.
  120. *
  121. * @private
  122. */
  123. async addAssets(compilation) {
  124. var _a;
  125. // See https://github.com/GoogleChrome/workbox/issues/1790
  126. if (this.alreadyCalled) {
  127. const warningMessage = `${this.constructor.name} has been called ` +
  128. `multiple times, perhaps due to running webpack in --watch mode. The ` +
  129. `precache manifest generated after the first call may be inaccurate! ` +
  130. `Please see https://github.com/GoogleChrome/workbox/issues/1790 for ` +
  131. `more information.`;
  132. if (!compilation.warnings.some((warning) => warning instanceof Error && warning.message === warningMessage)) {
  133. compilation.warnings.push(Error(warningMessage));
  134. }
  135. }
  136. else {
  137. this.alreadyCalled = true;
  138. }
  139. let config = {};
  140. try {
  141. // emit might be called multiple times; instead of modifying this.config,
  142. // use a validated copy.
  143. // See https://github.com/GoogleChrome/workbox/issues/2158
  144. config = (0, validate_options_1.validateWebpackGenerateSWOptions)(this.config);
  145. }
  146. catch (error) {
  147. if (error instanceof Error) {
  148. throw new Error(`Please check your ${this.constructor.name} plugin ` +
  149. `configuration:\n${error.message}`);
  150. }
  151. }
  152. // Ensure that we don't precache any of the assets generated by *any*
  153. // instance of this plugin.
  154. // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
  155. config.exclude.push(({ asset }) => _generatedAssetNames.has(asset.name));
  156. if (config.importScriptsViaChunks) {
  157. // Anything loaded via importScripts() is implicitly cached by the service
  158. // worker, and should not be added to the precache manifest.
  159. config.excludeChunks = (config.excludeChunks || []).concat(config.importScriptsViaChunks);
  160. const scripts = (0, get_script_files_for_chunks_1.getScriptFilesForChunks)(compilation, config.importScriptsViaChunks);
  161. config.importScripts = (config.importScripts || []).concat(scripts);
  162. }
  163. const { size, sortedEntries } = await (0, get_manifest_entries_from_compilation_1.getManifestEntriesFromCompilation)(compilation, config);
  164. config.manifestEntries = sortedEntries;
  165. const unbundledCode = (0, populate_sw_template_1.populateSWTemplate)(config);
  166. const files = await (0, bundle_1.bundle)({
  167. babelPresetEnvTargets: config.babelPresetEnvTargets,
  168. inlineWorkboxRuntime: config.inlineWorkboxRuntime,
  169. mode: config.mode,
  170. sourcemap: config.sourcemap,
  171. swDest: (0, relative_to_output_path_1.relativeToOutputPath)(compilation, config.swDest),
  172. unbundledCode,
  173. });
  174. for (const file of files) {
  175. compilation.emitAsset(file.name, new RawSource(Buffer.from(file.contents)), {
  176. // See https://github.com/webpack-contrib/compression-webpack-plugin/issues/218#issuecomment-726196160
  177. minimized: config.mode === 'production',
  178. });
  179. _generatedAssetNames.add(file.name);
  180. }
  181. if (compilation.getLogger) {
  182. const logger = compilation.getLogger(this.constructor.name);
  183. logger.info(`The service worker at ${(_a = config.swDest) !== null && _a !== void 0 ? _a : ''} will precache
  184. ${config.manifestEntries.length} URLs, totaling ${(0, pretty_bytes_1.default)(size)}.`);
  185. }
  186. }
  187. }
  188. exports.GenerateSW = GenerateSW;