ImportScriptsChunkLoadingRuntimeModule.js
8.0 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
/*
MIT License http://www.opensource.org/licenses/mit-license.php
*/
"use strict";
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 */
class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule {
/**
* @param {Set<string>} runtimeRequirements runtime requirements
* @param {boolean} withCreateScriptUrl with createScriptUrl support
*/
constructor(runtimeRequirements, withCreateScriptUrl) {
super("importScripts chunk loading", RuntimeModule.STAGE_ATTACH);
this.runtimeRequirements = runtimeRequirements;
this._withCreateScriptUrl = withCreateScriptUrl;
}
/**
* @private
* @param {Chunk} chunk chunk
* @returns {string} generated code
*/
_generateBaseUri(chunk) {
const options = chunk.getEntryOptions();
if (options && options.baseUri) {
return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`;
}
const outputName = this.compilation.getPath(
getChunkFilenameTemplate(chunk, this.compilation.outputOptions),
{
chunk,
contentHashType: "javascript"
}
);
const rootOutputDir = getUndoPath(
outputName,
/** @type {string} */ (this.compilation.outputOptions.path),
false
);
return `${RuntimeGlobals.baseURI} = self.location + ${JSON.stringify(
rootOutputDir ? "/../" + rootOutputDir : ""
)};`;
}
/**
* @returns {string} runtime code
*/
generate() {
const {
chunk,
chunkGraph,
compilation: {
runtimeTemplate,
outputOptions: { chunkLoadingGlobal, hotUpdateGlobal }
},
_withCreateScriptUrl: withCreateScriptUrl
} = this;
const globalObject = runtimeTemplate.globalObject;
const fn = RuntimeGlobals.ensureChunkHandlers;
const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI);
const withLoading = this.runtimeRequirements.has(
RuntimeGlobals.ensureChunkHandlers
);
const withHmr = this.runtimeRequirements.has(
RuntimeGlobals.hmrDownloadUpdateHandlers
);
const withHmrManifest = this.runtimeRequirements.has(
RuntimeGlobals.hmrDownloadManifest
);
const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify(
chunkLoadingGlobal
)}]`;
const hasJsMatcher = compileBooleanMatcher(
chunkGraph.getChunkConditionMap(chunk, chunkHasJs)
);
const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs);
const stateExpression = withHmr
? `${RuntimeGlobals.hmrRuntimeStatePrefix}_importScripts`
: undefined;
return Template.asString([
withBaseURI ? this._generateBaseUri(chunk) : "// no baseURI",
"",
"// object to store loaded chunks",
'// "1" means "already loaded"',
`var installedChunks = ${
stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
}{`,
Template.indent(
Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 1`).join(
",\n"
)
),
"};",
"",
withLoading
? Template.asString([
"// importScripts chunk loading",
`var installChunk = ${runtimeTemplate.basicFunction("data", [
runtimeTemplate.destructureArray(
["chunkIds", "moreModules", "runtime"],
"data"
),
"for(var moduleId in moreModules) {",
Template.indent([
`if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
Template.indent(
`${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];`
),
"}"
]),
"}",
`if(runtime) runtime(${RuntimeGlobals.require});`,
"while(chunkIds.length)",
Template.indent("installedChunks[chunkIds.pop()] = 1;"),
"parentChunkLoadingFunction(data);"
])};`
])
: "// no chunk install function needed",
withLoading
? Template.asString([
`${fn}.i = ${runtimeTemplate.basicFunction(
"chunkId, promises",
hasJsMatcher !== false
? [
'// "1" is the signal for "already loaded"',
"if(!installedChunks[chunkId]) {",
Template.indent([
hasJsMatcher === true
? "if(true) { // all chunks have JS"
: `if(${hasJsMatcher("chunkId")}) {`,
Template.indent(
`importScripts(${
withCreateScriptUrl
? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId))`
: `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId)`
});`
),
"}"
]),
"}"
]
: "installedChunks[chunkId] = 1;"
)};`,
"",
`var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`,
"var parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);",
"chunkLoadingGlobal.push = installChunk;"
])
: "// no chunk loading",
"",
withHmr
? Template.asString([
"function loadUpdateChunk(chunkId, updatedModulesList) {",
Template.indent([
"var success = false;",
`${globalObject}[${JSON.stringify(
hotUpdateGlobal
)}] = ${runtimeTemplate.basicFunction("_, moreModules, runtime", [
"for(var moduleId in moreModules) {",
Template.indent([
`if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
Template.indent([
"currentUpdate[moduleId] = moreModules[moduleId];",
"if(updatedModulesList) updatedModulesList.push(moduleId);"
]),
"}"
]),
"}",
"if(runtime) currentUpdateRuntime.push(runtime);",
"success = true;"
])};`,
"// start update chunk loading",
`importScripts(${
withCreateScriptUrl
? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId))`
: `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId)`
});`,
'if(!success) throw new Error("Loading update chunk failed for unknown reason");'
]),
"}",
"",
Template.getFunctionContent(
require("../hmr/JavascriptHotModuleReplacement.runtime.js")
)
.replace(/\$key\$/g, "importScrips")
.replace(/\$installedChunks\$/g, "installedChunks")
.replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk")
.replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache)
.replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories)
.replace(
/\$ensureChunkHandlers\$/g,
RuntimeGlobals.ensureChunkHandlers
)
.replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty)
.replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData)
.replace(
/\$hmrDownloadUpdateHandlers\$/g,
RuntimeGlobals.hmrDownloadUpdateHandlers
)
.replace(
/\$hmrInvalidateModuleHandlers\$/g,
RuntimeGlobals.hmrInvalidateModuleHandlers
)
])
: "// no HMR",
"",
withHmrManifest
? Template.asString([
`${
RuntimeGlobals.hmrDownloadManifest
} = ${runtimeTemplate.basicFunction("", [
'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");',
`return fetch(${RuntimeGlobals.publicPath} + ${
RuntimeGlobals.getUpdateManifestFilename
}()).then(${runtimeTemplate.basicFunction("response", [
"if(response.status === 404) return; // no update available",
'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);',
"return response.json();"
])});`
])};`
])
: "// no HMR manifest"
]);
}
}
module.exports = ImportScriptsChunkLoadingRuntimeModule;