DeterministicChunkIdsPlugin.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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) =>
  45. getFullChunkName(chunk, chunkGraph, context, compiler.root),
  46. compareNatural,
  47. (chunk, id) => {
  48. const size = usedIds.size;
  49. usedIds.add(`${id}`);
  50. if (size === usedIds.size) return false;
  51. chunk.id = id;
  52. chunk.ids = [id];
  53. return true;
  54. },
  55. [10 ** maxLength],
  56. 10,
  57. usedIds.size
  58. );
  59. });
  60. });
  61. }
  62. }
  63. module.exports = DeterministicChunkIdsPlugin;