DeterministicChunkIdsPlugin.js 2.0 KB

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