stringify-manifest.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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 stringify = require('json-stable-stringify');
  9. /**
  10. * The variable name that workbox-sw expects manifest entries to be assigned.
  11. * @type {String}
  12. * @private
  13. */
  14. const PRECACHE_MANIFEST_VAR = '__precacheManifest';
  15. /**
  16. * Generates a template string from an array of manifest entries that can be
  17. * written to a manifest file.
  18. *
  19. * @function generateManifestWithWebpack
  20. * @param {Array<module:workbox-build.ManifestEntry>} manifestEntries
  21. * @return {string} service worker manifest file string
  22. *
  23. * @private
  24. */
  25. module.exports = manifestEntries => {
  26. const sortedEntries = manifestEntries.sort((a, b) => a.url === b.url ? 0 : a.url > b.url ? 1 : -1); // json-stable-stringify ensures that we get a consistent output, with all
  27. // the properties of each object sorted.
  28. // There's a hash created of the serialized JSON data, and we want the hash to
  29. // be the same if the data is the same, without any sort-order variation.
  30. const entriesJson = stringify(sortedEntries, {
  31. space: 2
  32. });
  33. return `self.${PRECACHE_MANIFEST_VAR} = (self.${PRECACHE_MANIFEST_VAR} || ` + `[]).concat(${entriesJson});`;
  34. };