DeterministicChunkIdsPlugin.js 1.8 KB

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