AggressiveSplittingPlugin.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 createSchemaValidation = require("../util/create-schema-validation");
  13. const identifierUtils = require("../util/identifier");
  14. /** @typedef {import("../../declarations/plugins/optimize/AggressiveSplittingPlugin").AggressiveSplittingPluginOptions} AggressiveSplittingPluginOptions */
  15. /** @typedef {import("../Chunk")} Chunk */
  16. /** @typedef {import("../Chunk").ChunkId} ChunkId */
  17. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  18. /** @typedef {import("../Compiler")} Compiler */
  19. /** @typedef {import("../Module")} Module */
  20. const validate = createSchemaValidation(
  21. require("../../schemas/plugins/optimize/AggressiveSplittingPlugin.check"),
  22. () =>
  23. require("../../schemas/plugins/optimize/AggressiveSplittingPlugin.json"),
  24. {
  25. name: "Aggressive Splitting Plugin",
  26. baseDataPath: "options"
  27. }
  28. );
  29. /**
  30. * @param {ChunkGraph} chunkGraph the chunk graph
  31. * @param {Chunk} oldChunk the old chunk
  32. * @param {Chunk} newChunk the new chunk
  33. * @returns {(module: Module) => void} function to move module between chunks
  34. */
  35. const moveModuleBetween = (chunkGraph, oldChunk, newChunk) => (module) => {
  36. chunkGraph.disconnectChunkAndModule(oldChunk, module);
  37. chunkGraph.connectChunkAndModule(newChunk, module);
  38. };
  39. /**
  40. * @param {ChunkGraph} chunkGraph the chunk graph
  41. * @param {Chunk} chunk the chunk
  42. * @returns {(module: Module) => boolean} filter for entry module
  43. */
  44. const isNotAEntryModule = (chunkGraph, chunk) => (module) =>
  45. !chunkGraph.isEntryModuleInChunk(module, chunk);
  46. /** @typedef {{ id?: NonNullable<Chunk["id"]>, hash?: NonNullable<Chunk["hash"]>, modules: string[], size: number }} SplitData */
  47. /** @type {WeakSet<Chunk>} */
  48. const recordedChunks = new WeakSet();
  49. const PLUGIN_NAME = "AggressiveSplittingPlugin";
  50. class AggressiveSplittingPlugin {
  51. /**
  52. * @param {AggressiveSplittingPluginOptions=} options options object
  53. */
  54. constructor(options = {}) {
  55. validate(options);
  56. /** @type {AggressiveSplittingPluginOptions} */
  57. this.options = options;
  58. if (typeof this.options.minSize !== "number") {
  59. this.options.minSize = 30 * 1024;
  60. }
  61. if (typeof this.options.maxSize !== "number") {
  62. this.options.maxSize = 50 * 1024;
  63. }
  64. if (typeof this.options.chunkOverhead !== "number") {
  65. this.options.chunkOverhead = 0;
  66. }
  67. if (typeof this.options.entryChunkMultiplicator !== "number") {
  68. this.options.entryChunkMultiplicator = 1;
  69. }
  70. }
  71. /**
  72. * @param {Chunk} chunk the chunk to test
  73. * @returns {boolean} true if the chunk was recorded
  74. */
  75. static wasChunkRecorded(chunk) {
  76. return recordedChunks.has(chunk);
  77. }
  78. /**
  79. * Apply the plugin
  80. * @param {Compiler} compiler the compiler instance
  81. * @returns {void}
  82. */
  83. apply(compiler) {
  84. compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
  85. let needAdditionalSeal = false;
  86. /** @type {SplitData[]} */
  87. let newSplits;
  88. /** @type {Set<Chunk>} */
  89. let fromAggressiveSplittingSet;
  90. /** @type {Map<Chunk, SplitData>} */
  91. let chunkSplitDataMap;
  92. compilation.hooks.optimize.tap(PLUGIN_NAME, () => {
  93. newSplits = [];
  94. fromAggressiveSplittingSet = new Set();
  95. chunkSplitDataMap = new Map();
  96. });
  97. compilation.hooks.optimizeChunks.tap(
  98. {
  99. name: PLUGIN_NAME,
  100. stage: STAGE_ADVANCED
  101. },
  102. (chunks) => {
  103. const chunkGraph = compilation.chunkGraph;
  104. // Precompute stuff
  105. /** @type {Map<string, Module>} */
  106. const nameToModuleMap = new Map();
  107. /** @type {Map<Module, string>} */
  108. const moduleToNameMap = new Map();
  109. const makePathsRelative =
  110. identifierUtils.makePathsRelative.bindContextCache(
  111. compiler.context,
  112. compiler.root
  113. );
  114. for (const m of compilation.modules) {
  115. const name = makePathsRelative(m.identifier());
  116. nameToModuleMap.set(name, m);
  117. moduleToNameMap.set(m, name);
  118. }
  119. // Check used chunk ids
  120. /** @type {Set<ChunkId>} */
  121. const usedIds = new Set();
  122. for (const chunk of chunks) {
  123. usedIds.add(/** @type {ChunkId} */ (chunk.id));
  124. }
  125. const recordedSplits =
  126. (compilation.records && compilation.records.aggressiveSplits) || [];
  127. const usedSplits = newSplits
  128. ? [...recordedSplits, ...newSplits]
  129. : recordedSplits;
  130. const minSize = /** @type {number} */ (this.options.minSize);
  131. const maxSize = /** @type {number} */ (this.options.maxSize);
  132. /**
  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;