AggressiveSplittingPlugin.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 { intersect } = require("../util/SetHelpers");
  8. const {
  9. compareChunks,
  10. compareModulesByIdentifier
  11. } = require("../util/comparators");
  12. const identifierUtils = require("../util/identifier");
  13. /**
  14. * @import {
  15. * AggressiveSplittingPluginOptions
  16. * } from "../../declarations/plugins/optimize/AggressiveSplittingPlugin"
  17. */
  18. /** @import Chunk, { ChunkId } from "../Chunk" */
  19. /** @import ChunkGraph from "../ChunkGraph" */
  20. /** @import Compiler from "../Compiler" */
  21. /** @import Module from "../Module" */
  22. /**
  23. * Move module between.
  24. * @param {ChunkGraph} chunkGraph the chunk graph
  25. * @param {Chunk} oldChunk the old chunk
  26. * @param {Chunk} newChunk the new chunk
  27. * @returns {(module: Module) => void} function to move module between chunks
  28. */
  29. const moveModuleBetween = (chunkGraph, oldChunk, newChunk) => (module) => {
  30. chunkGraph.disconnectChunkAndModule(oldChunk, module);
  31. chunkGraph.connectChunkAndModule(newChunk, module);
  32. };
  33. /**
  34. * Checks whether this object is not a entry module.
  35. * @param {ChunkGraph} chunkGraph the chunk graph
  36. * @param {Chunk} chunk the chunk
  37. * @returns {(module: Module) => boolean} filter for entry module
  38. */
  39. const isNotAEntryModule = (chunkGraph, chunk) => (module) =>
  40. !chunkGraph.isEntryModuleInChunk(module, chunk);
  41. /** @typedef {{ id?: NonNullable<Chunk["id"]>, hash?: NonNullable<Chunk["hash"]>, modules: string[], size: number }} SplitData */
  42. /** @type {WeakSet<Chunk>} */
  43. const recordedChunks = new WeakSet();
  44. const PLUGIN_NAME = "AggressiveSplittingPlugin";
  45. class AggressiveSplittingPlugin {
  46. /**
  47. * Creates an instance of AggressiveSplittingPlugin.
  48. * @param {AggressiveSplittingPluginOptions=} options options object
  49. */
  50. constructor(options = {}) {
  51. /** @type {AggressiveSplittingPluginOptions} */
  52. this.options = options;
  53. }
  54. /**
  55. * Was chunk recorded.
  56. * @param {Chunk} chunk the chunk to test
  57. * @returns {boolean} true if the chunk was recorded
  58. */
  59. static wasChunkRecorded(chunk) {
  60. return recordedChunks.has(chunk);
  61. }
  62. /**
  63. * Applies the plugin by registering its hooks on the compiler.
  64. * @param {Compiler} compiler the compiler instance
  65. * @returns {void}
  66. */
  67. apply(compiler) {
  68. compiler.hooks.validate.tap(PLUGIN_NAME, () => {
  69. compiler.validate(
  70. () =>
  71. require("../../schemas/plugins/optimize/AggressiveSplittingPlugin.json"),
  72. this.options,
  73. {
  74. name: "Aggressive Splitting Plugin",
  75. baseDataPath: "options"
  76. },
  77. (options) =>
  78. require("../../schemas/plugins/optimize/AggressiveSplittingPlugin.check")(
  79. options
  80. )
  81. );
  82. });
  83. compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
  84. let needAdditionalSeal = false;
  85. /** @type {SplitData[]} */
  86. let newSplits;
  87. /** @type {Set<Chunk>} */
  88. let fromAggressiveSplittingSet;
  89. /** @type {Map<Chunk, SplitData>} */
  90. let chunkSplitDataMap;
  91. compilation.hooks.optimize.tap(PLUGIN_NAME, () => {
  92. newSplits = [];
  93. fromAggressiveSplittingSet = new Set();
  94. chunkSplitDataMap = new Map();
  95. });
  96. compilation.hooks.optimizeChunks.tap(
  97. {
  98. name: PLUGIN_NAME,
  99. stage: STAGE_ADVANCED
  100. },
  101. (chunks) => {
  102. const chunkGraph = compilation.chunkGraph;
  103. // Precompute stuff
  104. /** @type {Map<string, Module>} */
  105. const nameToModuleMap = new Map();
  106. /** @type {Map<Module, string>} */
  107. const moduleToNameMap = new Map();
  108. const makePathsRelative =
  109. identifierUtils.makePathsRelative.bindContextCache(
  110. compiler.context,
  111. compiler.root
  112. );
  113. for (const m of compilation.modules) {
  114. const name = makePathsRelative(m.identifier());
  115. nameToModuleMap.set(name, m);
  116. moduleToNameMap.set(m, name);
  117. }
  118. // Check used chunk ids
  119. /** @type {Set<ChunkId>} */
  120. const usedIds = new Set();
  121. for (const chunk of chunks) {
  122. usedIds.add(/** @type {ChunkId} */ (chunk.id));
  123. }
  124. const recordedSplits =
  125. (compilation.records && compilation.records.aggressiveSplits) || [];
  126. const usedSplits = newSplits
  127. ? [...recordedSplits, ...newSplits]
  128. : recordedSplits;
  129. const minSize = this.options.minSize || 30 * 1024;
  130. const maxSize = this.options.maxSize || 50 * 1024;
  131. /**
  132. * Returns true when applied, otherwise false.
  133. * @param {SplitData} splitData split data
  134. * @returns {boolean} true when applied, otherwise false
  135. */
  136. const applySplit = (splitData) => {
  137. // Cannot split if id is already taken
  138. if (splitData.id !== undefined && usedIds.has(splitData.id)) {
  139. return false;
  140. }
  141. // Get module objects from names
  142. const selectedModules = splitData.modules.map(
  143. (name) => /** @type {Module} */ (nameToModuleMap.get(name))
  144. );
  145. // Does the modules exist at all?
  146. if (!selectedModules.every(Boolean)) return false;
  147. // Check if size matches (faster than waiting for hash)
  148. let size = 0;
  149. for (const m of selectedModules) size += m.size();
  150. if (size !== splitData.size) return false;
  151. // get chunks with all modules
  152. const selectedChunks = intersect(
  153. selectedModules.map(
  154. (m) => new Set(chunkGraph.getModuleChunksIterable(m))
  155. )
  156. );
  157. // No relevant chunks found
  158. if (selectedChunks.size === 0) return false;
  159. // The found chunk is already the split or similar
  160. if (
  161. selectedChunks.size === 1 &&
  162. chunkGraph.getNumberOfChunkModules([...selectedChunks][0]) ===
  163. selectedModules.length
  164. ) {
  165. const chunk = [...selectedChunks][0];
  166. if (fromAggressiveSplittingSet.has(chunk)) return false;
  167. fromAggressiveSplittingSet.add(chunk);
  168. chunkSplitDataMap.set(chunk, splitData);
  169. return true;
  170. }
  171. // split the chunk into two parts
  172. const newChunk = compilation.addChunk();
  173. newChunk.chunkReason = "aggressive splitted";
  174. for (const chunk of selectedChunks) {
  175. for (const module of selectedModules) {
  176. moveModuleBetween(chunkGraph, chunk, newChunk)(module);
  177. }
  178. chunk.split(newChunk);
  179. chunk.name = null;
  180. }
  181. fromAggressiveSplittingSet.add(newChunk);
  182. chunkSplitDataMap.set(newChunk, splitData);
  183. if (splitData.id !== null && splitData.id !== undefined) {
  184. newChunk.id = splitData.id;
  185. newChunk.ids = [splitData.id];
  186. }
  187. return true;
  188. };
  189. // try to restore to recorded splitting
  190. let changed = false;
  191. for (let j = 0; j < usedSplits.length; j++) {
  192. const splitData = usedSplits[j];
  193. if (applySplit(splitData)) changed = true;
  194. }
  195. // for any chunk which isn't splitted yet, split it and create a new entry
  196. // start with the biggest chunk
  197. const cmpFn = compareChunks(chunkGraph);
  198. const sortedChunks = [...chunks].sort((a, b) => {
  199. const diff1 =
  200. chunkGraph.getChunkModulesSize(b) -
  201. chunkGraph.getChunkModulesSize(a);
  202. if (diff1) return diff1;
  203. const diff2 =
  204. chunkGraph.getNumberOfChunkModules(a) -
  205. chunkGraph.getNumberOfChunkModules(b);
  206. if (diff2) return diff2;
  207. return cmpFn(a, b);
  208. });
  209. for (const chunk of sortedChunks) {
  210. if (fromAggressiveSplittingSet.has(chunk)) continue;
  211. const size = chunkGraph.getChunkModulesSize(chunk);
  212. if (
  213. size > maxSize &&
  214. chunkGraph.getNumberOfChunkModules(chunk) > 1
  215. ) {
  216. const modules = chunkGraph
  217. .getOrderedChunkModules(chunk, compareModulesByIdentifier)
  218. .filter(isNotAEntryModule(chunkGraph, chunk));
  219. /** @type {Module[]} */
  220. const selectedModules = [];
  221. let selectedModulesSize = 0;
  222. for (let k = 0; k < modules.length; k++) {
  223. const module = modules[k];
  224. const newSize = selectedModulesSize + module.size();
  225. if (newSize > maxSize && selectedModulesSize >= minSize) {
  226. break;
  227. }
  228. selectedModulesSize = newSize;
  229. selectedModules.push(module);
  230. }
  231. if (selectedModules.length === 0) continue;
  232. /** @type {SplitData} */
  233. const splitData = {
  234. modules: selectedModules
  235. .map((m) => /** @type {string} */ (moduleToNameMap.get(m)))
  236. .sort(),
  237. size: selectedModulesSize
  238. };
  239. if (applySplit(splitData)) {
  240. newSplits = [...(newSplits || []), splitData];
  241. changed = true;
  242. }
  243. }
  244. }
  245. if (changed) return true;
  246. }
  247. );
  248. compilation.hooks.recordHash.tap(PLUGIN_NAME, (records) => {
  249. // 4. save made splittings to records
  250. /** @type {Set<SplitData>} */
  251. const allSplits = new Set();
  252. /** @type {Set<SplitData>} */
  253. const invalidSplits = new Set();
  254. // Check if some splittings are invalid
  255. // We remove invalid splittings and try again
  256. for (const chunk of compilation.chunks) {
  257. const splitData = chunkSplitDataMap.get(chunk);
  258. if (
  259. splitData !== undefined &&
  260. splitData.hash &&
  261. chunk.hash !== splitData.hash
  262. ) {
  263. // Split was successful, but hash doesn't equal
  264. // We can throw away the split since it's useless now
  265. invalidSplits.add(splitData);
  266. }
  267. }
  268. if (invalidSplits.size > 0) {
  269. records.aggressiveSplits =
  270. /** @type {SplitData[]} */
  271. (records.aggressiveSplits).filter(
  272. (splitData) => !invalidSplits.has(splitData)
  273. );
  274. needAdditionalSeal = true;
  275. } else {
  276. // set hash and id values on all (new) splittings
  277. for (const chunk of compilation.chunks) {
  278. const splitData = chunkSplitDataMap.get(chunk);
  279. if (splitData !== undefined) {
  280. splitData.hash =
  281. /** @type {NonNullable<Chunk["hash"]>} */
  282. (chunk.hash);
  283. splitData.id =
  284. /** @type {NonNullable<Chunk["id"]>} */
  285. (chunk.id);
  286. allSplits.add(splitData);
  287. // set flag for stats
  288. recordedChunks.add(chunk);
  289. }
  290. }
  291. // Also add all unused historical splits (after the used ones)
  292. // They can still be used in some future compilation
  293. const recordedSplits =
  294. compilation.records && compilation.records.aggressiveSplits;
  295. if (recordedSplits) {
  296. for (const splitData of recordedSplits) {
  297. if (!invalidSplits.has(splitData)) allSplits.add(splitData);
  298. }
  299. }
  300. // record all splits
  301. records.aggressiveSplits = [...allSplits];
  302. needAdditionalSeal = false;
  303. }
  304. });
  305. compilation.hooks.needAdditionalSeal.tap(PLUGIN_NAME, () => {
  306. if (needAdditionalSeal) {
  307. needAdditionalSeal = false;
  308. return true;
  309. }
  310. });
  311. });
  312. }
  313. }
  314. module.exports = AggressiveSplittingPlugin;