LimitChunkCountPlugin.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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 = /** @type {LimitChunkCountPluginOptions} */ (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 = options.maxChunks;
  70. if (!maxChunks) return;
  71. if (maxChunks < 1) return;
  72. if (compilation.chunks.size <= maxChunks) return;
  73. let remainingChunksToMerge = compilation.chunks.size - maxChunks;
  74. // order chunks in a deterministic way
  75. const compareChunksWithGraph = compareChunks(chunkGraph);
  76. const orderedChunks = Array.from(chunks).sort(compareChunksWithGraph);
  77. // create a lazy sorted data structure to keep all combinations
  78. // this is large. Size = chunks * (chunks - 1) / 2
  79. // It uses a multi layer bucket sort plus normal sort in the last layer
  80. // It's also lazy so only accessed buckets are sorted
  81. /** @type {LazyBucketSortedSet<ChunkCombination, number>} */
  82. const combinations = new LazyBucketSortedSet(
  83. // Layer 1: ordered by largest size benefit
  84. c => c.sizeDiff,
  85. (a, b) => b - a,
  86. // Layer 2: ordered by smallest combined size
  87. /**
  88. * @param {ChunkCombination} c combination
  89. * @returns {number} integrated size
  90. */
  91. c => c.integratedSize,
  92. /**
  93. * @param {number} a a
  94. * @param {number} b b
  95. * @returns {number} result
  96. */
  97. (a, b) => a - b,
  98. // Layer 3: ordered by position difference in orderedChunk (-> to be deterministic)
  99. /**
  100. * @param {ChunkCombination} c combination
  101. * @returns {number} position difference
  102. */
  103. c => c.bIdx - c.aIdx,
  104. /**
  105. * @param {number} a a
  106. * @param {number} b b
  107. * @returns {number} result
  108. */
  109. (a, b) => a - b,
  110. // Layer 4: ordered by position in orderedChunk (-> to be deterministic)
  111. /**
  112. * @param {ChunkCombination} a a
  113. * @param {ChunkCombination} b b
  114. * @returns {number} result
  115. */
  116. (a, b) => a.bIdx - b.bIdx
  117. );
  118. // we keep a mapping from chunk to all combinations
  119. // but this mapping is not kept up-to-date with deletions
  120. // so `deleted` flag need to be considered when iterating this
  121. /** @type {Map<Chunk, Set<ChunkCombination>>} */
  122. const combinationsByChunk = new Map();
  123. for (const [bIdx, b] of orderedChunks.entries()) {
  124. // create combination pairs with size and integrated size
  125. for (let aIdx = 0; aIdx < bIdx; aIdx++) {
  126. const a = orderedChunks[aIdx];
  127. // filter pairs that can not be integrated!
  128. if (!chunkGraph.canChunksBeIntegrated(a, b)) continue;
  129. const integratedSize = chunkGraph.getIntegratedChunksSize(
  130. a,
  131. b,
  132. options
  133. );
  134. const aSize = chunkGraph.getChunkSize(a, options);
  135. const bSize = chunkGraph.getChunkSize(b, options);
  136. /** @type {ChunkCombination} */
  137. const c = {
  138. deleted: false,
  139. sizeDiff: aSize + bSize - integratedSize,
  140. integratedSize,
  141. a,
  142. b,
  143. aIdx,
  144. bIdx,
  145. aSize,
  146. bSize
  147. };
  148. combinations.add(c);
  149. addToSetMap(combinationsByChunk, a, c);
  150. addToSetMap(combinationsByChunk, b, c);
  151. }
  152. }
  153. // list of modified chunks during this run
  154. // combinations affected by this change are skipped to allow
  155. // further optimizations
  156. /** @type {Set<Chunk>} */
  157. const modifiedChunks = new Set();
  158. let changed = false;
  159. loop: while (true) {
  160. const combination = combinations.popFirst();
  161. if (combination === undefined) break;
  162. combination.deleted = true;
  163. const { a, b, integratedSize } = combination;
  164. // skip over pair when
  165. // one of the already merged chunks is a parent of one of the chunks
  166. if (modifiedChunks.size > 0) {
  167. const queue = new Set(a.groupsIterable);
  168. for (const group of b.groupsIterable) {
  169. queue.add(group);
  170. }
  171. for (const group of queue) {
  172. for (const mChunk of modifiedChunks) {
  173. if (mChunk !== a && mChunk !== b && mChunk.isInGroup(group)) {
  174. // This is a potential pair which needs recalculation
  175. // We can't do that now, but it merge before following pairs
  176. // so we leave space for it, and consider chunks as modified
  177. // just for the worse case
  178. remainingChunksToMerge--;
  179. if (remainingChunksToMerge <= 0) break loop;
  180. modifiedChunks.add(a);
  181. modifiedChunks.add(b);
  182. continue loop;
  183. }
  184. }
  185. for (const parent of group.parentsIterable) {
  186. queue.add(parent);
  187. }
  188. }
  189. }
  190. // merge the chunks
  191. if (chunkGraph.canChunksBeIntegrated(a, b)) {
  192. chunkGraph.integrateChunks(a, b);
  193. compilation.chunks.delete(b);
  194. // flag chunk a as modified as further optimization are possible for all children here
  195. modifiedChunks.add(a);
  196. changed = true;
  197. remainingChunksToMerge--;
  198. if (remainingChunksToMerge <= 0) break;
  199. // Update all affected combinations
  200. // delete all combination with the removed chunk
  201. // we will use combinations with the kept chunk instead
  202. for (const combination of /** @type {Set<ChunkCombination>} */ (
  203. combinationsByChunk.get(a)
  204. )) {
  205. if (combination.deleted) continue;
  206. combination.deleted = true;
  207. combinations.delete(combination);
  208. }
  209. // Update combinations with the kept chunk with new sizes
  210. for (const combination of /** @type {Set<ChunkCombination>} */ (
  211. combinationsByChunk.get(b)
  212. )) {
  213. if (combination.deleted) continue;
  214. if (combination.a === b) {
  215. if (!chunkGraph.canChunksBeIntegrated(a, combination.b)) {
  216. combination.deleted = true;
  217. combinations.delete(combination);
  218. continue;
  219. }
  220. // Update size
  221. const newIntegratedSize = chunkGraph.getIntegratedChunksSize(
  222. a,
  223. combination.b,
  224. options
  225. );
  226. const finishUpdate = combinations.startUpdate(combination);
  227. combination.a = a;
  228. combination.integratedSize = newIntegratedSize;
  229. combination.aSize = integratedSize;
  230. combination.sizeDiff =
  231. combination.bSize + integratedSize - newIntegratedSize;
  232. finishUpdate();
  233. } else if (combination.b === b) {
  234. if (!chunkGraph.canChunksBeIntegrated(combination.a, a)) {
  235. combination.deleted = true;
  236. combinations.delete(combination);
  237. continue;
  238. }
  239. // Update size
  240. const newIntegratedSize = chunkGraph.getIntegratedChunksSize(
  241. combination.a,
  242. a,
  243. options
  244. );
  245. const finishUpdate = combinations.startUpdate(combination);
  246. combination.b = a;
  247. combination.integratedSize = newIntegratedSize;
  248. combination.bSize = integratedSize;
  249. combination.sizeDiff =
  250. integratedSize + combination.aSize - newIntegratedSize;
  251. finishUpdate();
  252. }
  253. }
  254. combinationsByChunk.set(
  255. a,
  256. /** @type {Set<ChunkCombination>} */ (
  257. combinationsByChunk.get(b)
  258. )
  259. );
  260. combinationsByChunk.delete(b);
  261. }
  262. }
  263. if (changed) return true;
  264. }
  265. );
  266. });
  267. }
  268. }
  269. module.exports = LimitChunkCountPlugin;