DeterministicChunkIdsPlugin.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Florent Cailhol @ooflorent
  4. */
  5. "use strict";
  6. const { compareChunksNatural } = require("../util/comparators");
  7. const {
  8. getFullChunkName,
  9. getUsedChunkIds,
  10. assignDeterministicIds
  11. } = require("./IdHelpers");
  12. /** @typedef {import("../Compiler")} Compiler */
  13. /** @typedef {import("../Module")} Module */
  14. /**
  15. * @typedef {object} DeterministicChunkIdsPluginOptions
  16. * @property {string=} context context for ids
  17. * @property {number=} maxLength maximum length of ids
  18. */
  19. class DeterministicChunkIdsPlugin {
  20. /**
  21. * @param {DeterministicChunkIdsPluginOptions} [options] options
  22. */
  23. constructor(options = {}) {
  24. this.options = options;
  25. }
  26. /**
  27. * Apply the plugin
  28. * @param {Compiler} compiler the compiler instance
  29. * @returns {void}
  30. */
  31. apply(compiler) {
  32. compiler.hooks.compilation.tap(
  33. "DeterministicChunkIdsPlugin",
  34. compilation => {
  35. compilation.hooks.chunkIds.tap(
  36. "DeterministicChunkIdsPlugin",
  37. chunks => {
  38. const chunkGraph = compilation.chunkGraph;
  39. const context = this.options.context
  40. ? this.options.context
  41. : compiler.context;
  42. const maxLength = this.options.maxLength || 3;
  43. const compareNatural = compareChunksNatural(chunkGraph);
  44. const usedIds = getUsedChunkIds(compilation);
  45. assignDeterministicIds(
  46. Array.from(chunks).filter(chunk => {
  47. return chunk.id === null;
  48. }),
  49. chunk =>
  50. getFullChunkName(chunk, chunkGraph, context, compiler.root),
  51. compareNatural,
  52. (chunk, id) => {
  53. const size = usedIds.size;
  54. usedIds.add(`${id}`);
  55. if (size === usedIds.size) return false;
  56. chunk.id = id;
  57. chunk.ids = [id];
  58. return true;
  59. },
  60. [Math.pow(10, maxLength)],
  61. 10,
  62. usedIds.size
  63. );
  64. }
  65. );
  66. }
  67. );
  68. }
  69. }
  70. module.exports = DeterministicChunkIdsPlugin;