source: frontend/node_modules/webpack/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 11 days ago

Fix frontend appearance

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