source: imaps-frontend/node_modules/webpack/lib/node/ReadFileChunkLoadingRuntimeModule.js@ 79a0317

main
Last change on this file since 79a0317 was 79a0317, checked in by stefan toskovski <stefantoska84@…>, 3 days ago

F4 Finalna Verzija

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