UNPKG

2.54 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5
6"use strict";
7
8const { STAGE_BASIC } = require("../OptimizationStages");
9
10/** @typedef {import("../Chunk")} Chunk */
11/** @typedef {import("../ChunkGroup")} ChunkGroup */
12/** @typedef {import("../Compiler")} Compiler */
13
14class EnsureChunkConditionsPlugin {
15 /**
16 * Apply the plugin
17 * @param {Compiler} compiler the compiler instance
18 * @returns {void}
19 */
20 apply(compiler) {
21 compiler.hooks.compilation.tap(
22 "EnsureChunkConditionsPlugin",
23 compilation => {
24 const handler = chunks => {
25 const chunkGraph = compilation.chunkGraph;
26 // These sets are hoisted here to save memory
27 // They are cleared at the end of every loop
28 /** @type {Set<Chunk>} */
29 const sourceChunks = new Set();
30 /** @type {Set<ChunkGroup>} */
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 /** @type {Set<Chunk>} */
44 const targetChunks = new Set();
45 chunkGroupLoop: for (const chunkGroup of chunkGroups) {
46 // Can module be placed in a chunk of this group?
47 for (const chunk of chunkGroup.chunks) {
48 if (module.chunkCondition(chunk, compilation)) {
49 targetChunks.add(chunk);
50 continue chunkGroupLoop;
51 }
52 }
53 // We reached the entrypoint: fail
54 if (chunkGroup.isInitial()) {
55 throw new Error(
56 "Cannot fullfil chunk condition of " + module.identifier()
57 );
58 }
59 // Try placing in all parents
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}
85module.exports = EnsureChunkConditionsPlugin;