You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.0 KiB

4 years ago
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const validateOptions = require("schema-utils");
  7. const schema = require("../../schemas/plugins/optimize/OccurrenceOrderChunkIdsPlugin.json");
  8. /** @typedef {import("../../declarations/plugins/optimize/OccurrenceOrderChunkIdsPlugin").OccurrenceOrderChunkIdsPluginOptions} OccurrenceOrderChunkIdsPluginOptions */
  9. class OccurrenceOrderChunkIdsPlugin {
  10. /**
  11. * @param {OccurrenceOrderChunkIdsPluginOptions=} options options object
  12. */
  13. constructor(options = {}) {
  14. validateOptions(schema, options, "Occurrence Order Chunk Ids Plugin");
  15. this.options = options;
  16. }
  17. apply(compiler) {
  18. const prioritiseInitial = this.options.prioritiseInitial;
  19. compiler.hooks.compilation.tap(
  20. "OccurrenceOrderChunkIdsPlugin",
  21. compilation => {
  22. compilation.hooks.optimizeChunkOrder.tap(
  23. "OccurrenceOrderChunkIdsPlugin",
  24. chunks => {
  25. const occursInInitialChunksMap = new Map();
  26. const originalOrder = new Map();
  27. let i = 0;
  28. for (const c of chunks) {
  29. let occurs = 0;
  30. for (const chunkGroup of c.groupsIterable) {
  31. for (const parent of chunkGroup.parentsIterable) {
  32. if (parent.isInitial()) occurs++;
  33. }
  34. }
  35. occursInInitialChunksMap.set(c, occurs);
  36. originalOrder.set(c, i++);
  37. }
  38. chunks.sort((a, b) => {
  39. if (prioritiseInitial) {
  40. const aEntryOccurs = occursInInitialChunksMap.get(a);
  41. const bEntryOccurs = occursInInitialChunksMap.get(b);
  42. if (aEntryOccurs > bEntryOccurs) return -1;
  43. if (aEntryOccurs < bEntryOccurs) return 1;
  44. }
  45. const aOccurs = a.getNumberOfGroups();
  46. const bOccurs = b.getNumberOfGroups();
  47. if (aOccurs > bOccurs) return -1;
  48. if (aOccurs < bOccurs) return 1;
  49. const orgA = originalOrder.get(a);
  50. const orgB = originalOrder.get(b);
  51. return orgA - orgB;
  52. });
  53. }
  54. );
  55. }
  56. );
  57. }
  58. }
  59. module.exports = OccurrenceOrderChunkIdsPlugin;