source: frontend/node_modules/webpack/lib/node/ReadFileChunkLoadingRuntimeModule.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: 10.2 KB
RevLine 
[9af201e]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("../RuntimeTemplate")} RuntimeTemplate */
25/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
26
27class ReadFileChunkLoadingRuntimeModule extends RuntimeModule {
28 /**
29 * Creates an instance of ReadFileChunkLoadingRuntimeModule.
30 * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements
31 */
32 constructor(runtimeRequirements) {
33 super("readFile chunk loading", RuntimeModule.STAGE_ATTACH);
34 /** @type {ReadOnlyRuntimeRequirements} */
35 this.runtimeRequirements = runtimeRequirements;
36 }
37
38 /**
39 * Returns generated code.
40 * @private
41 * @param {Chunk} chunk chunk
42 * @param {string} rootOutputDir root output directory
43 * @param {RuntimeTemplate} runtimeTemplate the runtime template
44 * @returns {string} generated code
45 */
46 _generateBaseUri(chunk, rootOutputDir, runtimeTemplate) {
47 const options = chunk.getEntryOptions();
48 if (options && options.baseUri) {
49 return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`;
50 }
51
52 return `${RuntimeGlobals.baseURI} = require(${runtimeTemplate.renderNodePrefixForCoreModule("url")}).pathToFileURL(${
53 rootOutputDir
54 ? `__dirname + ${JSON.stringify(`/${rootOutputDir}`)}`
55 : "__filename"
56 });`;
57 }
58
59 /**
60 * Generates runtime code for this runtime module.
61 * @returns {string | null} runtime code
62 */
63 generate() {
64 const compilation = /** @type {Compilation} */ (this.compilation);
65 const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
66 const chunk = /** @type {Chunk} */ (this.chunk);
67 const { runtimeTemplate } = compilation;
68 const fn = RuntimeGlobals.ensureChunkHandlers;
69 const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI);
70 const withExternalInstallChunk = this.runtimeRequirements.has(
71 RuntimeGlobals.externalInstallChunk
72 );
73 const withOnChunkLoad = this.runtimeRequirements.has(
74 RuntimeGlobals.onChunksLoaded
75 );
76 const withLoading = this.runtimeRequirements.has(
77 RuntimeGlobals.ensureChunkHandlers
78 );
79 const withHmr = this.runtimeRequirements.has(
80 RuntimeGlobals.hmrDownloadUpdateHandlers
81 );
82 const withHmrManifest = this.runtimeRequirements.has(
83 RuntimeGlobals.hmrDownloadManifest
84 );
85 const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs);
86 const hasJsMatcher = compileBooleanMatcher(conditionMap);
87 const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs);
88
89 const outputName = compilation.getPath(
90 getChunkFilenameTemplate(chunk, compilation.outputOptions),
91 {
92 chunk,
93 contentHashType: "javascript"
94 }
95 );
96 const rootOutputDir = getUndoPath(
97 outputName,
98 compilation.outputOptions.path,
99 false
100 );
101
102 const stateExpression = withHmr
103 ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_readFileVm`
104 : undefined;
105
106 return Template.asString([
107 withBaseURI
108 ? this._generateBaseUri(chunk, rootOutputDir, runtimeTemplate)
109 : "// no baseURI",
110 "",
111 "// object to store loaded chunks",
112 '// "0" means "already loaded", Promise means loading',
113 `var installedChunks = ${
114 stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
115 }{`,
116 Template.indent(
117 Array.from(initialChunkIds, (id) => `${JSON.stringify(id)}: 0`).join(
118 ",\n"
119 )
120 ),
121 "};",
122 "",
123 withOnChunkLoad
124 ? `${
125 RuntimeGlobals.onChunksLoaded
126 }.readFileVm = ${runtimeTemplate.returningFunction(
127 "installedChunks[chunkId] === 0",
128 "chunkId"
129 )};`
130 : "// no on chunks loaded",
131 "",
132 withLoading || withExternalInstallChunk
133 ? `var installChunk = ${runtimeTemplate.basicFunction("chunk", [
134 "var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;",
135 "for(var moduleId in moreModules) {",
136 Template.indent([
137 `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
138 Template.indent([
139 `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];`
140 ]),
141 "}"
142 ]),
143 "}",
144 `if(runtime) runtime(${RuntimeGlobals.require});`,
145 "for(var i = 0; i < chunkIds.length; i++) {",
146 Template.indent([
147 "if(installedChunks[chunkIds[i]]) {",
148 Template.indent(["installedChunks[chunkIds[i]][0]();"]),
149 "}",
150 "installedChunks[chunkIds[i]] = 0;"
151 ]),
152 "}",
153 withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : ""
154 ])};`
155 : "// no chunk install function needed",
156 "",
157 withLoading
158 ? Template.asString([
159 "// ReadFile + VM.run chunk loading for javascript",
160 `${fn}.readFileVm = function(chunkId, promises) {`,
161 hasJsMatcher !== false
162 ? Template.indent([
163 "",
164 "var installedChunkData = installedChunks[chunkId];",
165 'if(installedChunkData !== 0) { // 0 means "already installed".',
166 Template.indent([
167 '// array of [resolve, reject, promise] means "currently loading"',
168 "if(installedChunkData) {",
169 Template.indent(["promises.push(installedChunkData[2]);"]),
170 "} else {",
171 Template.indent([
172 hasJsMatcher === true
173 ? "if(true) { // all chunks have JS"
174 : `if(${hasJsMatcher("chunkId")}) {`,
175 Template.indent([
176 "// load the chunk and return promise to it",
177 "var promise = new Promise(function(resolve, reject) {",
178 Template.indent([
179 "installedChunkData = installedChunks[chunkId] = [resolve, reject];",
180 `var filename = require(${runtimeTemplate.renderNodePrefixForCoreModule("path")}).join(__dirname, ${JSON.stringify(
181 rootOutputDir
182 )} + ${
183 RuntimeGlobals.getChunkScriptFilename
184 }(chunkId));`,
185 `require(${runtimeTemplate.renderNodePrefixForCoreModule("fs")}).readFile(filename, 'utf-8', function(err, content) {`,
186 Template.indent([
187 "if(err) return reject(err);",
188 "var chunk = {};",
189 `require(${runtimeTemplate.renderNodePrefixForCoreModule("vm")}).runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)` +
190 `(chunk, require, require(${runtimeTemplate.renderNodePrefixForCoreModule("path")}).dirname(filename), filename);`,
191 "installChunk(chunk);"
192 ]),
193 "});"
194 ]),
195 "});",
196 "promises.push(installedChunkData[2] = promise);"
197 ]),
198 hasJsMatcher === true
199 ? "}"
200 : "} else installedChunks[chunkId] = 0;"
201 ]),
202 "}"
203 ]),
204 "}"
205 ])
206 : Template.indent(["installedChunks[chunkId] = 0;"]),
207 "};"
208 ])
209 : "// no chunk loading",
210 "",
211 withExternalInstallChunk
212 ? Template.asString([
213 `module.exports = ${RuntimeGlobals.require};`,
214 `${RuntimeGlobals.externalInstallChunk} = installChunk;`
215 ])
216 : "// no external install chunk",
217 "",
218 withHmr
219 ? Template.asString([
220 "function loadUpdateChunk(chunkId, updatedModulesList) {",
221 Template.indent([
222 "return new Promise(function(resolve, reject) {",
223 Template.indent([
224 `var filename = require(${runtimeTemplate.renderNodePrefixForCoreModule("path")}).join(__dirname, ${JSON.stringify(
225 rootOutputDir
226 )} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId));`,
227 `require(${runtimeTemplate.renderNodePrefixForCoreModule("fs")}).readFile(filename, 'utf-8', function(err, content) {`,
228 Template.indent([
229 "if(err) return reject(err);",
230 "var update = {};",
231 `require(${runtimeTemplate.renderNodePrefixForCoreModule("vm")}).runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)` +
232 `(update, require, require(${runtimeTemplate.renderNodePrefixForCoreModule("path")}).dirname(filename), filename);`,
233 "var updatedModules = update.modules;",
234 "var runtime = update.runtime;",
235 "for(var moduleId in updatedModules) {",
236 Template.indent([
237 `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`,
238 Template.indent([
239 "currentUpdate[moduleId] = updatedModules[moduleId];",
240 "if(updatedModulesList) updatedModulesList.push(moduleId);"
241 ]),
242 "}"
243 ]),
244 "}",
245 "if(runtime) currentUpdateRuntime.push(runtime);",
246 "resolve();"
247 ]),
248 "});"
249 ]),
250 "});"
251 ]),
252 "}",
253 "",
254 generateJavascriptHMR("readFileVm")
255 ])
256 : "// no HMR",
257 "",
258 withHmrManifest
259 ? Template.asString([
260 `${RuntimeGlobals.hmrDownloadManifest} = function() {`,
261 Template.indent([
262 "return new Promise(function(resolve, reject) {",
263 Template.indent([
264 `var filename = require(${runtimeTemplate.renderNodePrefixForCoreModule("path")}).join(__dirname, ${JSON.stringify(
265 rootOutputDir
266 )} + ${RuntimeGlobals.getUpdateManifestFilename}());`,
267 `require(${runtimeTemplate.renderNodePrefixForCoreModule("fs")}).readFile(filename, 'utf-8', function(err, content) {`,
268 Template.indent([
269 "if(err) {",
270 Template.indent([
271 'if(["MODULE_NOT_FOUND", "ENOENT"].includes(err.code)) return resolve();',
272 "return reject(err);"
273 ]),
274 "}",
275 "try { resolve(JSON.parse(content)); }",
276 "catch(e) { reject(e); }"
277 ]),
278 "});"
279 ]),
280 "});"
281 ]),
282 "}"
283 ])
284 : "// no HMR manifest"
285 ]);
286 }
287}
288
289module.exports = ReadFileChunkLoadingRuntimeModule;
Note: See TracBrowser for help on using the repository browser.