1 |
|
2 |
|
3 |
|
4 |
|
5 | "use strict";
|
6 |
|
7 | const RuntimeGlobals = require("../RuntimeGlobals");
|
8 | const RuntimeModule = require("../RuntimeModule");
|
9 | const Template = require("../Template");
|
10 | const {
|
11 | getChunkFilenameTemplate,
|
12 | chunkHasJs
|
13 | } = require("../javascript/JavascriptModulesPlugin");
|
14 | const { getInitialChunkIds } = require("../javascript/StartupHelpers");
|
15 | const compileBooleanMatcher = require("../util/compileBooleanMatcher");
|
16 | const { getUndoPath } = require("../util/identifier");
|
17 |
|
18 |
|
19 |
|
20 | class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule {
|
21 | constructor(runtimeRequirements, withCreateScriptUrl) {
|
22 | super("importScripts chunk loading", RuntimeModule.STAGE_ATTACH);
|
23 | this.runtimeRequirements = runtimeRequirements;
|
24 | this._withCreateScriptUrl = withCreateScriptUrl;
|
25 | }
|
26 |
|
27 | |
28 |
|
29 |
|
30 |
|
31 |
|
32 | _generateBaseUri(chunk) {
|
33 | const options = chunk.getEntryOptions();
|
34 | if (options && options.baseUri) {
|
35 | return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`;
|
36 | }
|
37 | const outputName = this.compilation.getPath(
|
38 | getChunkFilenameTemplate(chunk, this.compilation.outputOptions),
|
39 | {
|
40 | chunk,
|
41 | contentHashType: "javascript"
|
42 | }
|
43 | );
|
44 | const rootOutputDir = getUndoPath(
|
45 | outputName,
|
46 | this.compilation.outputOptions.path,
|
47 | false
|
48 | );
|
49 | return `${RuntimeGlobals.baseURI} = self.location + ${JSON.stringify(
|
50 | rootOutputDir ? "/../" + rootOutputDir : ""
|
51 | )};`;
|
52 | }
|
53 |
|
54 | |
55 |
|
56 |
|
57 | generate() {
|
58 | const {
|
59 | chunk,
|
60 | chunkGraph,
|
61 | compilation: {
|
62 | runtimeTemplate,
|
63 | outputOptions: { chunkLoadingGlobal, hotUpdateGlobal }
|
64 | },
|
65 | _withCreateScriptUrl: withCreateScriptUrl
|
66 | } = this;
|
67 | const globalObject = runtimeTemplate.globalObject;
|
68 | const fn = RuntimeGlobals.ensureChunkHandlers;
|
69 | const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI);
|
70 | const withLoading = this.runtimeRequirements.has(
|
71 | RuntimeGlobals.ensureChunkHandlers
|
72 | );
|
73 | const withHmr = this.runtimeRequirements.has(
|
74 | RuntimeGlobals.hmrDownloadUpdateHandlers
|
75 | );
|
76 | const withHmrManifest = this.runtimeRequirements.has(
|
77 | RuntimeGlobals.hmrDownloadManifest
|
78 | );
|
79 | const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify(
|
80 | chunkLoadingGlobal
|
81 | )}]`;
|
82 | const hasJsMatcher = compileBooleanMatcher(
|
83 | chunkGraph.getChunkConditionMap(chunk, chunkHasJs)
|
84 | );
|
85 | const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs);
|
86 |
|
87 | const stateExpression = withHmr
|
88 | ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_importScripts`
|
89 | : undefined;
|
90 |
|
91 | return Template.asString([
|
92 | withBaseURI ? this._generateBaseUri(chunk) : "// no baseURI",
|
93 | "",
|
94 | "// object to store loaded chunks",
|
95 | '// "1" means "already loaded"',
|
96 | `var installedChunks = ${
|
97 | stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
|
98 | }{`,
|
99 | Template.indent(
|
100 | Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 1`).join(
|
101 | ",\n"
|
102 | )
|
103 | ),
|
104 | "};",
|
105 | "",
|
106 | withLoading
|
107 | ? Template.asString([
|
108 | "// importScripts chunk loading",
|
109 | `var installChunk = ${runtimeTemplate.basicFunction("data", [
|
110 | runtimeTemplate.destructureArray(
|
111 | ["chunkIds", "moreModules", "runtime"],
|
112 | "data"
|
113 | ),
|
114 | "for(var moduleId in moreModules) {",
|
115 | Template.indent([
|
116 | `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
|
117 | Template.indent(
|
118 | `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];`
|
119 | ),
|
120 | "}"
|
121 | ]),
|
122 | "}",
|
123 | "if(runtime) runtime(__webpack_require__);",
|
124 | "while(chunkIds.length)",
|
125 | Template.indent("installedChunks[chunkIds.pop()] = 1;"),
|
126 | "parentChunkLoadingFunction(data);"
|
127 | ])};`
|
128 | ])
|
129 | : "// no chunk install function needed",
|
130 | withLoading
|
131 | ? Template.asString([
|
132 | `${fn}.i = ${runtimeTemplate.basicFunction(
|
133 | "chunkId, promises",
|
134 | hasJsMatcher !== false
|
135 | ? [
|
136 | '// "1" is the signal for "already loaded"',
|
137 | "if(!installedChunks[chunkId]) {",
|
138 | Template.indent([
|
139 | hasJsMatcher === true
|
140 | ? "if(true) { // all chunks have JS"
|
141 | : `if(${hasJsMatcher("chunkId")}) {`,
|
142 | Template.indent(
|
143 | `importScripts(${
|
144 | withCreateScriptUrl
|
145 | ? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId))`
|
146 | : `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId)`
|
147 | });`
|
148 | ),
|
149 | "}"
|
150 | ]),
|
151 | "}"
|
152 | ]
|
153 | : "installedChunks[chunkId] = 1;"
|
154 | )};`,
|
155 | "",
|
156 | `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`,
|
157 | "var parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);",
|
158 | "chunkLoadingGlobal.push = installChunk;"
|
159 | ])
|
160 | : "// no chunk loading",
|
161 | "",
|
162 | withHmr
|
163 | ? Template.asString([
|
164 | "function loadUpdateChunk(chunkId, updatedModulesList) {",
|
165 | Template.indent([
|
166 | "var success = false;",
|
167 | `${globalObject}[${JSON.stringify(
|
168 | hotUpdateGlobal
|
169 | )}] = ${runtimeTemplate.basicFunction("_, moreModules, runtime", [
|
170 | "for(var moduleId in moreModules) {",
|
171 | Template.indent([
|
172 | `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
|
173 | Template.indent([
|
174 | "currentUpdate[moduleId] = moreModules[moduleId];",
|
175 | "if(updatedModulesList) updatedModulesList.push(moduleId);"
|
176 | ]),
|
177 | "}"
|
178 | ]),
|
179 | "}",
|
180 | "if(runtime) currentUpdateRuntime.push(runtime);",
|
181 | "success = true;"
|
182 | ])};`,
|
183 | "// start update chunk loading",
|
184 | `importScripts(${
|
185 | withCreateScriptUrl
|
186 | ? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId))`
|
187 | : `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId)`
|
188 | });`,
|
189 | 'if(!success) throw new Error("Loading update chunk failed for unknown reason");'
|
190 | ]),
|
191 | "}",
|
192 | "",
|
193 | Template.getFunctionContent(
|
194 | require("../hmr/JavascriptHotModuleReplacement.runtime.js")
|
195 | )
|
196 | .replace(/\$key\$/g, "importScrips")
|
197 | .replace(/\$installedChunks\$/g, "installedChunks")
|
198 | .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk")
|
199 | .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache)
|
200 | .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories)
|
201 | .replace(
|
202 | /\$ensureChunkHandlers\$/g,
|
203 | RuntimeGlobals.ensureChunkHandlers
|
204 | )
|
205 | .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty)
|
206 | .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData)
|
207 | .replace(
|
208 | /\$hmrDownloadUpdateHandlers\$/g,
|
209 | RuntimeGlobals.hmrDownloadUpdateHandlers
|
210 | )
|
211 | .replace(
|
212 | /\$hmrInvalidateModuleHandlers\$/g,
|
213 | RuntimeGlobals.hmrInvalidateModuleHandlers
|
214 | )
|
215 | ])
|
216 | : "// no HMR",
|
217 | "",
|
218 | withHmrManifest
|
219 | ? Template.asString([
|
220 | `${
|
221 | RuntimeGlobals.hmrDownloadManifest
|
222 | } = ${runtimeTemplate.basicFunction("", [
|
223 | 'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");',
|
224 | `return fetch(${RuntimeGlobals.publicPath} + ${
|
225 | RuntimeGlobals.getUpdateManifestFilename
|
226 | }()).then(${runtimeTemplate.basicFunction("response", [
|
227 | "if(response.status === 404) return; // no update available",
|
228 | 'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);',
|
229 | "return response.json();"
|
230 | ])});`
|
231 | ])};`
|
232 | ])
|
233 | : "// no HMR manifest"
|
234 | ]);
|
235 | }
|
236 | }
|
237 |
|
238 | module.exports = ImportScriptsChunkLoadingRuntimeModule;
|