You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

inject-manifest.js 10 KiB

3 vuotta sitten
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. 'use strict';
  2. var _regenerator = require('babel-runtime/regenerator');
  3. var _regenerator2 = _interopRequireDefault(_regenerator);
  4. var _stringify = require('babel-runtime/core-js/json/stringify');
  5. var _stringify2 = _interopRequireDefault(_stringify);
  6. var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');
  7. var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);
  8. var _keys = require('babel-runtime/core-js/object/keys');
  9. var _keys2 = _interopRequireDefault(_keys);
  10. var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
  11. var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
  12. var _assign = require('babel-runtime/core-js/object/assign');
  13. var _assign2 = _interopRequireDefault(_assign);
  14. var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
  15. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  16. var _createClass2 = require('babel-runtime/helpers/createClass');
  17. var _createClass3 = _interopRequireDefault(_createClass2);
  18. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  19. /*
  20. Copyright 2017 Google Inc.
  21. Licensed under the Apache License, Version 2.0 (the "License");
  22. you may not use this file except in compliance with the License.
  23. You may obtain a copy of the License at
  24. https://www.apache.org/licenses/LICENSE-2.0
  25. Unless required by applicable law or agreed to in writing, software
  26. distributed under the License is distributed on an "AS IS" BASIS,
  27. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  28. See the License for the specific language governing permissions and
  29. limitations under the License.
  30. */
  31. var assert = require('assert');
  32. var path = require('path');
  33. var _require = require('workbox-build'),
  34. getManifest = _require.getManifest;
  35. var convertStringToAsset = require('./lib/convert-string-to-asset');
  36. var getDefaultConfig = require('./lib/get-default-config');
  37. var formatManifestFilename = require('./lib/format-manifest-filename');
  38. var getAssetHash = require('./lib/get-asset-hash');
  39. var getManifestEntriesFromCompilation = require('./lib/get-manifest-entries-from-compilation');
  40. var getWorkboxSWImports = require('./lib/get-workbox-sw-imports');
  41. var readFileWrapper = require('./lib/read-file-wrapper');
  42. var relativeToOutputPath = require('./lib/relative-to-output-path');
  43. var sanitizeConfig = require('./lib/sanitize-config');
  44. var stringifyManifest = require('./lib/stringify-manifest');
  45. var warnAboutConfig = require('./lib/warn-about-config');
  46. /**
  47. * This class supports taking an existing service worker file which already
  48. * uses Workbox, and injecting a reference to a [precache manifest]() into it,
  49. * allowing it to efficiently precache the assets created by a webpack build.
  50. *
  51. * Use an instance of `InjectManifest` in the
  52. * [`plugins` array](https://webpack.js.org/concepts/plugins/#usage) of a
  53. * webpack config.
  54. *
  55. * @module workbox-webpack-plugin
  56. */
  57. var InjectManifest = function () {
  58. /**
  59. * Creates an instance of InjectManifest.
  60. *
  61. * @param {Object} [config] See the
  62. * [configuration guide](https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin#configuration)
  63. * for all supported options and defaults.
  64. */
  65. function InjectManifest() {
  66. var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  67. (0, _classCallCheck3.default)(this, InjectManifest);
  68. assert(typeof config.swSrc === 'string', `swSrc must be set to the path ` + `to an existing service worker file.`);
  69. this.config = (0, _assign2.default)(getDefaultConfig(), {
  70. // Default to using the same filename as the swSrc file, since that's
  71. // provided here. (In GenerateSW, that's not available.)
  72. swDest: path.basename(config.swSrc)
  73. }, config);
  74. }
  75. /**
  76. * @param {Object} compilation The webpack compilation.
  77. * @param {Function} readFile The function to use when reading files,
  78. * derived from compiler.inputFileSystem.
  79. * @private
  80. */
  81. (0, _createClass3.default)(InjectManifest, [{
  82. key: 'handleEmit',
  83. value: function () {
  84. var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(compilation, readFile) {
  85. var configWarning, workboxSWImports, modulePathPrefix, entries, importScriptsArray, sanitizedConfig, _ref2, manifestEntries, warnings, manifestString, manifestAsset, manifestHash, manifestFilename, pathToManifestFile, originalSWString, absoluteSwSrc, importScriptsString, setConfigString, postInjectionSWString, relSwDest;
  86. return _regenerator2.default.wrap(function _callee$(_context) {
  87. while (1) {
  88. switch (_context.prev = _context.next) {
  89. case 0:
  90. configWarning = warnAboutConfig(this.config);
  91. if (configWarning) {
  92. compilation.warnings.push(configWarning);
  93. }
  94. _context.next = 4;
  95. return getWorkboxSWImports(compilation, this.config);
  96. case 4:
  97. workboxSWImports = _context.sent;
  98. // this.config.modulePathPrefix may or may not have been set by
  99. // getWorkboxSWImports(), depending on the other config options. If it was
  100. // set, we need to pull it out and make use of it later, as it can't be
  101. // used by the underlying workbox-build getManifest() method.
  102. modulePathPrefix = this.config.modulePathPrefix;
  103. delete this.config.modulePathPrefix;
  104. entries = getManifestEntriesFromCompilation(compilation, this.config);
  105. importScriptsArray = [].concat(this.config.importScripts);
  106. sanitizedConfig = sanitizeConfig.forGetManifest(this.config);
  107. // If there are any "extra" config options remaining after we remove the
  108. // ones that are used natively by the plugin, then assume that they should
  109. // be passed on to workbox-build.getManifest() to generate extra entries.
  110. if (!((0, _keys2.default)(sanitizedConfig).length > 0)) {
  111. _context.next = 19;
  112. break;
  113. }
  114. // If globPatterns isn't explicitly set, then default to [], instead of
  115. // the workbox-build.getManifest() default.
  116. sanitizedConfig.globPatterns = sanitizedConfig.globPatterns || [];
  117. _context.next = 14;
  118. return getManifest(sanitizedConfig);
  119. case 14:
  120. _ref2 = _context.sent;
  121. manifestEntries = _ref2.manifestEntries;
  122. warnings = _ref2.warnings;
  123. compilation.warnings = compilation.warnings.concat(warnings || []);
  124. entries = entries.concat(manifestEntries);
  125. case 19:
  126. manifestString = stringifyManifest(entries);
  127. manifestAsset = convertStringToAsset(manifestString);
  128. manifestHash = getAssetHash(manifestAsset);
  129. manifestFilename = formatManifestFilename(this.config.precacheManifestFilename, manifestHash);
  130. pathToManifestFile = relativeToOutputPath(compilation, path.join(this.config.importsDirectory, manifestFilename));
  131. compilation.assets[pathToManifestFile] = manifestAsset;
  132. importScriptsArray.push((compilation.options.output.publicPath || '') + pathToManifestFile.split(path.sep).join('/'));
  133. // workboxSWImports might be null if importWorkboxFrom is 'disabled'.
  134. if (workboxSWImports) {
  135. importScriptsArray.push.apply(importScriptsArray, (0, _toConsumableArray3.default)(workboxSWImports));
  136. }
  137. _context.next = 29;
  138. return readFileWrapper(readFile, this.config.swSrc);
  139. case 29:
  140. originalSWString = _context.sent;
  141. // compilation.fileDependencies needs absolute paths.
  142. absoluteSwSrc = path.resolve(this.config.swSrc);
  143. if (Array.isArray(compilation.fileDependencies)) {
  144. // webpack v3
  145. if (compilation.fileDependencies.indexOf(absoluteSwSrc) === -1) {
  146. compilation.fileDependencies.push(absoluteSwSrc);
  147. }
  148. } else if ('add' in compilation.fileDependencies) {
  149. // webpack v4; no need to check for membership first, since it's a Set.
  150. compilation.fileDependencies.add(absoluteSwSrc);
  151. }
  152. importScriptsString = importScriptsArray.map(_stringify2.default).join(', ');
  153. setConfigString = modulePathPrefix ? `workbox.setConfig({modulePathPrefix: ` + `${(0, _stringify2.default)(modulePathPrefix)}});` : '';
  154. postInjectionSWString = `importScripts(${importScriptsString});
  155. ${setConfigString}
  156. ${originalSWString}
  157. `;
  158. relSwDest = relativeToOutputPath(compilation, this.config.swDest);
  159. compilation.assets[relSwDest] = convertStringToAsset(postInjectionSWString);
  160. case 37:
  161. case 'end':
  162. return _context.stop();
  163. }
  164. }
  165. }, _callee, this);
  166. }));
  167. function handleEmit(_x2, _x3) {
  168. return _ref.apply(this, arguments);
  169. }
  170. return handleEmit;
  171. }()
  172. /**
  173. * @param {Object} [compiler] default compiler object passed from webpack
  174. *
  175. * @private
  176. */
  177. }, {
  178. key: 'apply',
  179. value: function apply(compiler) {
  180. var _this = this;
  181. var readFile = compiler.inputFileSystem.readFile.bind(compiler.inputFileSystem);
  182. if ('hooks' in compiler) {
  183. // We're in webpack 4+.
  184. compiler.hooks.emit.tapPromise(this.constructor.name, function (compilation) {
  185. return _this.handleEmit(compilation, readFile);
  186. });
  187. } else {
  188. // We're in webpack 2 or 3.
  189. compiler.plugin('emit', function (compilation, callback) {
  190. _this.handleEmit(compilation, readFile).then(callback).catch(callback);
  191. });
  192. }
  193. }
  194. }]);
  195. return InjectManifest;
  196. }();
  197. module.exports = InjectManifest;