1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | "use strict";
|
7 |
|
8 | const { STAGE_BASIC } = require("../OptimizationStages");
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | class EnsureChunkConditionsPlugin {
|
15 | |
16 |
|
17 |
|
18 |
|
19 |
|
20 | apply(compiler) {
|
21 | compiler.hooks.compilation.tap(
|
22 | "EnsureChunkConditionsPlugin",
|
23 | compilation => {
|
24 | const handler = chunks => {
|
25 | const chunkGraph = compilation.chunkGraph;
|
26 |
|
27 |
|
28 |
|
29 | const sourceChunks = new Set();
|
30 |
|
31 | const chunkGroups = new Set();
|
32 | for (const module of compilation.modules) {
|
33 | if (!module.hasChunkCondition()) continue;
|
34 | for (const chunk of chunkGraph.getModuleChunksIterable(module)) {
|
35 | if (!module.chunkCondition(chunk, compilation)) {
|
36 | sourceChunks.add(chunk);
|
37 | for (const group of chunk.groupsIterable) {
|
38 | chunkGroups.add(group);
|
39 | }
|
40 | }
|
41 | }
|
42 | if (sourceChunks.size === 0) continue;
|
43 |
|
44 | const targetChunks = new Set();
|
45 | chunkGroupLoop: for (const chunkGroup of chunkGroups) {
|
46 |
|
47 | for (const chunk of chunkGroup.chunks) {
|
48 | if (module.chunkCondition(chunk, compilation)) {
|
49 | targetChunks.add(chunk);
|
50 | continue chunkGroupLoop;
|
51 | }
|
52 | }
|
53 |
|
54 | if (chunkGroup.isInitial()) {
|
55 | throw new Error(
|
56 | "Cannot fullfil chunk condition of " + module.identifier()
|
57 | );
|
58 | }
|
59 |
|
60 | for (const group of chunkGroup.parentsIterable) {
|
61 | chunkGroups.add(group);
|
62 | }
|
63 | }
|
64 | for (const sourceChunk of sourceChunks) {
|
65 | chunkGraph.disconnectChunkAndModule(sourceChunk, module);
|
66 | }
|
67 | for (const targetChunk of targetChunks) {
|
68 | chunkGraph.connectChunkAndModule(targetChunk, module);
|
69 | }
|
70 | sourceChunks.clear();
|
71 | chunkGroups.clear();
|
72 | }
|
73 | };
|
74 | compilation.hooks.optimizeChunks.tap(
|
75 | {
|
76 | name: "EnsureChunkConditionsPlugin",
|
77 | stage: STAGE_BASIC
|
78 | },
|
79 | handler
|
80 | );
|
81 | }
|
82 | );
|
83 | }
|
84 | }
|
85 | module.exports = EnsureChunkConditionsPlugin;
|