OccurrenceChunkIdsPlugin.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { compareChunksNatural } = require("../util/comparators");
  7. const createSchemaValidation = require("../util/create-schema-validation");
  8. const { assignAscendingChunkIds } = require("./IdHelpers");
  9. /** @typedef {import("../../declarations/plugins/ids/OccurrenceChunkIdsPlugin").OccurrenceChunkIdsPluginOptions} OccurrenceChunkIdsPluginOptions */
  10. /** @typedef {import("../Chunk")} Chunk */
  11. /** @typedef {import("../Compiler")} Compiler */
  12. /** @typedef {import("../Module")} Module */
  13. const validate = createSchemaValidation(
  14. require("../../schemas/plugins/ids/OccurrenceChunkIdsPlugin.check.js"),
  15. () => require("../../schemas/plugins/ids/OccurrenceChunkIdsPlugin.json"),
  16. {
  17. name: "Occurrence Order Chunk Ids Plugin",
  18. baseDataPath: "options"
  19. }
  20. );
  21. class OccurrenceChunkIdsPlugin {
  22. /**
  23. * @param {OccurrenceChunkIdsPluginOptions=} options options object
  24. */
  25. constructor(options = {}) {
  26. validate(options);
  27. this.options = options;
  28. }
  29. /**
  30. * Apply the plugin
  31. * @param {Compiler} compiler the compiler instance
  32. * @returns {void}
  33. */
  34. apply(compiler) {
  35. const prioritiseInitial = this.options.prioritiseInitial;
  36. compiler.hooks.compilation.tap("OccurrenceChunkIdsPlugin", compilation => {
  37. compilation.hooks.chunkIds.tap("OccurrenceChunkIdsPlugin", chunks => {
  38. const chunkGraph = compilation.chunkGraph;
  39. /** @type {Map<Chunk, number>} */
  40. const occursInInitialChunksMap = new Map();
  41. const compareNatural = compareChunksNatural(chunkGraph);
  42. for (const c of chunks) {
  43. let occurs = 0;
  44. for (const chunkGroup of c.groupsIterable) {
  45. for (const parent of chunkGroup.parentsIterable) {
  46. if (parent.isInitial()) occurs++;
  47. }
  48. }
  49. occursInInitialChunksMap.set(c, occurs);
  50. }
  51. const chunksInOccurrenceOrder = Array.from(chunks).sort((a, b) => {
  52. if (prioritiseInitial) {
  53. const aEntryOccurs = occursInInitialChunksMap.get(a);
  54. const bEntryOccurs = occursInInitialChunksMap.get(b);
  55. if (aEntryOccurs > bEntryOccurs) return -1;
  56. if (aEntryOccurs < bEntryOccurs) return 1;
  57. }
  58. const aOccurs = a.getNumberOfGroups();
  59. const bOccurs = b.getNumberOfGroups();
  60. if (aOccurs > bOccurs) return -1;
  61. if (aOccurs < bOccurs) return 1;
  62. return compareNatural(a, b);
  63. });
  64. assignAscendingChunkIds(chunksInOccurrenceOrder, compilation);
  65. });
  66. });
  67. }
  68. }
  69. module.exports = OccurrenceChunkIdsPlugin;