AggressiveSplittingPlugin.js 9.9 KB

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