LimitChunkCountPlugin.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { STAGE_ADVANCED } = require("../OptimizationStages");
  7. const LazyBucketSortedSet = require("../util/LazyBucketSortedSet");
  8. const { compareChunks } = require("../util/comparators");
  9. const createSchemaValidation = require("../util/create-schema-validation");
  10. /** @typedef {import("../../declarations/plugins/optimize/LimitChunkCountPlugin").LimitChunkCountPluginOptions} LimitChunkCountPluginOptions */
  11. /** @typedef {import("../Chunk")} Chunk */
  12. /** @typedef {import("../Compiler")} Compiler */
  13. const validate = createSchemaValidation(
  14. require("../../schemas/plugins/optimize/LimitChunkCountPlugin.check.js"),
  15. () => require("../../schemas/plugins/optimize/LimitChunkCountPlugin.json"),
  16. {
  17. name: "Limit Chunk Count Plugin",
  18. baseDataPath: "options"
  19. }
  20. );
  21. /**
  22. * @typedef {Object} ChunkCombination
  23. * @property {boolean} deleted this is set to true when combination was removed
  24. * @property {number} sizeDiff
  25. * @property {number} integratedSize
  26. * @property {Chunk} a
  27. * @property {Chunk} b
  28. * @property {number} aIdx
  29. * @property {number} bIdx
  30. * @property {number} aSize
  31. * @property {number} bSize
  32. */
  33. /**
  34. * @template K, V
  35. * @param {Map<K, Set<V>>} map map
  36. * @param {K} key key
  37. * @param {V} value value
  38. */
  39. const addToSetMap = (map, key, value) => {
  40. const set = map.get(key);
  41. if (set === undefined) {
  42. map.set(key, new Set([value]));
  43. } else {
  44. set.add(value);
  45. }
  46. };
  47. class LimitChunkCountPlugin {
  48. /**
  49. * @param {LimitChunkCountPluginOptions=} options options object
  50. */
  51. constructor(options) {
  52. validate(options);
  53. this.options = options;
  54. }
  55. /**
  56. * @param {Compiler} compiler the webpack compiler
  57. * @returns {void}
  58. */
  59. apply(compiler) {
  60. const options = this.options;
  61. compiler.hooks.compilation.tap("LimitChunkCountPlugin", compilation => {
  62. compilation.hooks.optimizeChunks.tap(
  63. {
  64. name: "LimitChunkCountPlugin",
  65. stage: STAGE_ADVANCED
  66. },
  67. chunks => {
  68. const chunkGraph = compilation.chunkGraph;
  69. const maxChunks =
  70. /** @type {LimitChunkCountPluginOptions} */
  71. (options).maxChunks;
  72. if (!maxChunks) return;
  73. if (maxChunks < 1) return;
  74. if (compilation.chunks.size <= maxChunks) return;
  75. let remainingChunksToMerge = compilation.chunks.size - maxChunks;
  76. // order chunks in a deterministic way
  77. const compareChunksWithGraph = compareChunks(chunkGraph);
  78. const orderedChunks = Array.from(chunks).sort(compareChunksWithGraph);
  79. // create a lazy sorted data structure to keep all combinations
  80. // this is large. Size = chunks * (chunks - 1) / 2
  81. // It uses a multi layer bucket sort plus normal sort in the last layer
  82. // It's also lazy so only accessed buckets are sorted
  83. const combinations = new LazyBucketSortedSet(
  84. // Layer 1: ordered by largest size benefit
  85. c => c.sizeDiff,
  86. (a, b) => b - a,
  87. // Layer 2: ordered by smallest combined size
  88. /**
  89. * @param {ChunkCombination} c combination
  90. * @returns {number} integrated size
  91. */
  92. c => c.integratedSize,
  93. (a, b) => a - b,
  94. // Layer 3: ordered by position difference in orderedChunk (-> to be deterministic)
  95. /**
  96. * @param {ChunkCombination} c combination
  97. * @returns {number} position difference
  98. */
  99. c => c.bIdx - c.aIdx,
  100. (a, b) => a - b,
  101. // Layer 4: ordered by position in orderedChunk (-> to be deterministic)
  102. (a, b) => a.bIdx - b.bIdx
  103. );
  104. // we keep a mapping from chunk to all combinations
  105. // but this mapping is not kept up-to-date with deletions
  106. // so `deleted` flag need to be considered when iterating this
  107. /** @type {Map<Chunk, Set<ChunkCombination>>} */
  108. const combinationsByChunk = new Map();
  109. orderedChunks.forEach((b, bIdx) => {
  110. // create combination pairs with size and integrated size
  111. for (let aIdx = 0; aIdx < bIdx; aIdx++) {
  112. const a = orderedChunks[aIdx];
  113. // filter pairs that can not be integrated!
  114. if (!chunkGraph.canChunksBeIntegrated(a, b)) continue;
  115. const integratedSize = chunkGraph.getIntegratedChunksSize(
  116. a,
  117. b,
  118. options
  119. );
  120. const aSize = chunkGraph.getChunkSize(a, options);
  121. const bSize = chunkGraph.getChunkSize(b, options);
  122. const c = {
  123. deleted: false,
  124. sizeDiff: aSize + bSize - integratedSize,
  125. integratedSize,
  126. a,
  127. b,
  128. aIdx,
  129. bIdx,
  130. aSize,
  131. bSize
  132. };
  133. combinations.add(c);
  134. addToSetMap(combinationsByChunk, a, c);
  135. addToSetMap(combinationsByChunk, b, c);
  136. }
  137. return combinations;
  138. });
  139. // list of modified chunks during this run
  140. // combinations affected by this change are skipped to allow
  141. // further optimizations
  142. /** @type {Set<Chunk>} */
  143. const modifiedChunks = new Set();
  144. let changed = false;
  145. // eslint-disable-next-line no-constant-condition
  146. loop: while (true) {
  147. const combination = combinations.popFirst();
  148. if (combination === undefined) break;
  149. combination.deleted = true;
  150. const { a, b, integratedSize } = combination;
  151. // skip over pair when
  152. // one of the already merged chunks is a parent of one of the chunks
  153. if (modifiedChunks.size > 0) {
  154. const queue = new Set(a.groupsIterable);
  155. for (const group of b.groupsIterable) {
  156. queue.add(group);
  157. }
  158. for (const group of queue) {
  159. for (const mChunk of modifiedChunks) {
  160. if (mChunk !== a && mChunk !== b && mChunk.isInGroup(group)) {
  161. // This is a potential pair which needs recalculation
  162. // We can't do that now, but it merge before following pairs
  163. // so we leave space for it, and consider chunks as modified
  164. // just for the worse case
  165. remainingChunksToMerge--;
  166. if (remainingChunksToMerge <= 0) break loop;
  167. modifiedChunks.add(a);
  168. modifiedChunks.add(b);
  169. continue loop;
  170. }
  171. }
  172. for (const parent of group.parentsIterable) {
  173. queue.add(parent);
  174. }
  175. }
  176. }
  177. // merge the chunks
  178. if (chunkGraph.canChunksBeIntegrated(a, b)) {
  179. chunkGraph.integrateChunks(a, b);
  180. compilation.chunks.delete(b);
  181. // flag chunk a as modified as further optimization are possible for all children here
  182. modifiedChunks.add(a);
  183. changed = true;
  184. remainingChunksToMerge--;
  185. if (remainingChunksToMerge <= 0) break;
  186. // Update all affected combinations
  187. // delete all combination with the removed chunk
  188. // we will use combinations with the kept chunk instead
  189. for (const combination of /** @type {Set<ChunkCombination>} */ (
  190. combinationsByChunk.get(a)
  191. )) {
  192. if (combination.deleted) continue;
  193. combination.deleted = true;
  194. combinations.delete(combination);
  195. }
  196. // Update combinations with the kept chunk with new sizes
  197. for (const combination of /** @type {Set<ChunkCombination>} */ (
  198. combinationsByChunk.get(b)
  199. )) {
  200. if (combination.deleted) continue;
  201. if (combination.a === b) {
  202. if (!chunkGraph.canChunksBeIntegrated(a, combination.b)) {
  203. combination.deleted = true;
  204. combinations.delete(combination);
  205. continue;
  206. }
  207. // Update size
  208. const newIntegratedSize = chunkGraph.getIntegratedChunksSize(
  209. a,
  210. combination.b,
  211. options
  212. );
  213. const finishUpdate = combinations.startUpdate(combination);
  214. combination.a = a;
  215. combination.integratedSize = newIntegratedSize;
  216. combination.aSize = integratedSize;
  217. combination.sizeDiff =
  218. combination.bSize + integratedSize - newIntegratedSize;
  219. finishUpdate();
  220. } else if (combination.b === b) {
  221. if (!chunkGraph.canChunksBeIntegrated(combination.a, a)) {
  222. combination.deleted = true;
  223. combinations.delete(combination);
  224. continue;
  225. }
  226. // Update size
  227. const newIntegratedSize = chunkGraph.getIntegratedChunksSize(
  228. combination.a,
  229. a,
  230. options
  231. );
  232. const finishUpdate = combinations.startUpdate(combination);
  233. combination.b = a;
  234. combination.integratedSize = newIntegratedSize;
  235. combination.bSize = integratedSize;
  236. combination.sizeDiff =
  237. integratedSize + combination.aSize - newIntegratedSize;
  238. finishUpdate();
  239. }
  240. }
  241. combinationsByChunk.set(
  242. a,
  243. /** @type {Set<ChunkCombination>} */ (
  244. combinationsByChunk.get(b)
  245. )
  246. );
  247. combinationsByChunk.delete(b);
  248. }
  249. }
  250. if (changed) return true;
  251. }
  252. );
  253. });
  254. }
  255. }
  256. module.exports = LimitChunkCountPlugin;