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