ModuleChunkLoadingRuntimeModule.js
7.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
/*
MIT License http://www.opensource.org/licenses/mit-license.php
*/
"use strict";
const { SyncWaterfallHook } = require("tapable");
const Compilation = require("../Compilation");
const RuntimeGlobals = require("../RuntimeGlobals");
const RuntimeModule = require("../RuntimeModule");
const Template = require("../Template");
const {
getChunkFilenameTemplate,
chunkHasJs
} = require("../javascript/JavascriptModulesPlugin");
const { getInitialChunkIds } = require("../javascript/StartupHelpers");
const compileBooleanMatcher = require("../util/compileBooleanMatcher");
const { getUndoPath } = require("../util/identifier");
/** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../ChunkGraph")} ChunkGraph */
/**
* @typedef {Object} JsonpCompilationPluginHooks
* @property {SyncWaterfallHook<[string, Chunk]>} linkPreload
* @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch
*/
/** @type {WeakMap<Compilation, JsonpCompilationPluginHooks>} */
const compilationHooksMap = new WeakMap();
class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
/**
* @param {Compilation} compilation the compilation
* @returns {JsonpCompilationPluginHooks} hooks
*/
static getCompilationHooks(compilation) {
if (!(compilation instanceof Compilation)) {
throw new TypeError(
"The 'compilation' argument must be an instance of Compilation"
);
}
let hooks = compilationHooksMap.get(compilation);
if (hooks === undefined) {
hooks = {
linkPreload: new SyncWaterfallHook(["source", "chunk"]),
linkPrefetch: new SyncWaterfallHook(["source", "chunk"])
};
compilationHooksMap.set(compilation, hooks);
}
return hooks;
}
/**
* @param {ReadonlySet<string>} runtimeRequirements runtime requirements
*/
constructor(runtimeRequirements) {
super("import chunk loading", RuntimeModule.STAGE_ATTACH);
this._runtimeRequirements = runtimeRequirements;
}
/**
* @private
* @param {Chunk} chunk chunk
* @param {string} rootOutputDir root output directory
* @returns {string} generated code
*/
_generateBaseUri(chunk, rootOutputDir) {
const options = chunk.getEntryOptions();
if (options && options.baseUri) {
return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`;
}
const compilation = /** @type {Compilation} */ (this.compilation);
const {
outputOptions: { importMetaName }
} = compilation;
return `${RuntimeGlobals.baseURI} = new URL(${JSON.stringify(
rootOutputDir
)}, ${importMetaName}.url);`;
}
/**
* @returns {string} runtime code
*/
generate() {
const compilation = /** @type {Compilation} */ (this.compilation);
const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
const chunk = /** @type {Chunk} */ (this.chunk);
const {
runtimeTemplate,
outputOptions: { importFunctionName }
} = compilation;
const fn = RuntimeGlobals.ensureChunkHandlers;
const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI);
const withExternalInstallChunk = this._runtimeRequirements.has(
RuntimeGlobals.externalInstallChunk
);
const withLoading = this._runtimeRequirements.has(
RuntimeGlobals.ensureChunkHandlers
);
const withOnChunkLoad = this._runtimeRequirements.has(
RuntimeGlobals.onChunksLoaded
);
const withHmr = this._runtimeRequirements.has(
RuntimeGlobals.hmrDownloadUpdateHandlers
);
const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs);
const hasJsMatcher = compileBooleanMatcher(conditionMap);
const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs);
const outputName = compilation.getPath(
getChunkFilenameTemplate(chunk, compilation.outputOptions),
{
chunk,
contentHashType: "javascript"
}
);
const rootOutputDir = getUndoPath(
outputName,
/** @type {string} */ (compilation.outputOptions.path),
true
);
const stateExpression = withHmr
? `${RuntimeGlobals.hmrRuntimeStatePrefix}_module`
: undefined;
return Template.asString([
withBaseURI
? this._generateBaseUri(chunk, rootOutputDir)
: "// no baseURI",
"",
"// object to store loaded and loading chunks",
"// undefined = chunk not loaded, null = chunk preloaded/prefetched",
"// [resolve, Promise] = chunk loading, 0 = chunk loaded",
`var installedChunks = ${
stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
}{`,
Template.indent(
Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join(
",\n"
)
),
"};",
"",
withLoading || withExternalInstallChunk
? `var installChunk = ${runtimeTemplate.basicFunction("data", [
runtimeTemplate.destructureObject(
["ids", "modules", "runtime"],
"data"
),
'// add "modules" to the modules object,',
'// then flag all "ids" as loaded and fire callback',
"var moduleId, chunkId, i = 0;",
"for(moduleId in modules) {",
Template.indent([
`if(${RuntimeGlobals.hasOwnProperty}(modules, moduleId)) {`,
Template.indent(
`${RuntimeGlobals.moduleFactories}[moduleId] = modules[moduleId];`
),
"}"
]),
"}",
`if(runtime) runtime(${RuntimeGlobals.require});`,
"for(;i < ids.length; i++) {",
Template.indent([
"chunkId = ids[i];",
`if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`,
Template.indent("installedChunks[chunkId][0]();"),
"}",
"installedChunks[ids[i]] = 0;"
]),
"}",
withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : ""
])}`
: "// no install chunk",
"",
withLoading
? Template.asString([
`${fn}.j = ${runtimeTemplate.basicFunction(
"chunkId, promises",
hasJsMatcher !== false
? Template.indent([
"// import() chunk loading for javascript",
`var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`,
'if(installedChunkData !== 0) { // 0 means "already installed".',
Template.indent([
"",
'// a Promise means "currently loading".',
"if(installedChunkData) {",
Template.indent([
"promises.push(installedChunkData[1]);"
]),
"} else {",
Template.indent([
hasJsMatcher === true
? "if(true) { // all chunks have JS"
: `if(${hasJsMatcher("chunkId")}) {`,
Template.indent([
"// setup Promise in chunk cache",
`var promise = ${importFunctionName}(${JSON.stringify(
rootOutputDir
)} + ${
RuntimeGlobals.getChunkScriptFilename
}(chunkId)).then(installChunk, ${runtimeTemplate.basicFunction(
"e",
[
"if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;",
"throw e;"
]
)});`,
`var promise = Promise.race([promise, new Promise(${runtimeTemplate.expressionFunction(
`installedChunkData = installedChunks[chunkId] = [resolve]`,
"resolve"
)})])`,
`promises.push(installedChunkData[1] = promise);`
]),
hasJsMatcher === true
? "}"
: "} else installedChunks[chunkId] = 0;"
]),
"}"
]),
"}"
])
: Template.indent(["installedChunks[chunkId] = 0;"])
)};`
])
: "// no chunk on demand loading",
"",
withExternalInstallChunk
? Template.asString([
`${RuntimeGlobals.externalInstallChunk} = installChunk;`
])
: "// no external install chunk",
"",
withOnChunkLoad
? `${
RuntimeGlobals.onChunksLoaded
}.j = ${runtimeTemplate.returningFunction(
"installedChunks[chunkId] === 0",
"chunkId"
)};`
: "// no on chunks loaded"
]);
}
}
module.exports = ModuleChunkLoadingRuntimeModule;