DeterministicChunkIdsPlugin.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. class DeterministicChunkIdsPlugin {
  15. constructor(options) {
  16. this.options = options || {};
  17. }
  18. /**
  19. * Apply the plugin
  20. * @param {Compiler} compiler the compiler instance
  21. * @returns {void}
  22. */
  23. apply(compiler) {
  24. compiler.hooks.compilation.tap(
  25. "DeterministicChunkIdsPlugin",
  26. compilation => {
  27. compilation.hooks.chunkIds.tap(
  28. "DeterministicChunkIdsPlugin",
  29. chunks => {
  30. const chunkGraph = compilation.chunkGraph;
  31. const context = this.options.context
  32. ? this.options.context
  33. : compiler.context;
  34. const maxLength = this.options.maxLength || 3;
  35. const compareNatural = compareChunksNatural(chunkGraph);
  36. const usedIds = getUsedChunkIds(compilation);
  37. assignDeterministicIds(
  38. Array.from(chunks).filter(chunk => {
  39. return chunk.id === null;
  40. }),
  41. chunk =>
  42. getFullChunkName(chunk, chunkGraph, context, compiler.root),
  43. compareNatural,
  44. (chunk, id) => {
  45. const size = usedIds.size;
  46. usedIds.add(`${id}`);
  47. if (size === usedIds.size) return false;
  48. chunk.id = id;
  49. chunk.ids = [id];
  50. return true;
  51. },
  52. [Math.pow(10, maxLength)],
  53. 10,
  54. usedIds.size
  55. );
  56. }
  57. );
  58. }
  59. );
  60. }
  61. }
  62. module.exports = DeterministicChunkIdsPlugin;