10
0

DeterministicChunkIdsPlugin.js 1.9 KB

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