source: frontend/node_modules/webpack/lib/css/CssLoadingRuntimeModule.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: 18.2 KB
Line 
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5
6"use strict";
7
8const { SyncWaterfallHook } = require("tapable");
9const Compilation = require("../Compilation");
10const { CSS_TYPE } = require("../ModuleSourceTypeConstants");
11const RuntimeGlobals = require("../RuntimeGlobals");
12const RuntimeModule = require("../RuntimeModule");
13const Template = require("../Template");
14const compileBooleanMatcher = require("../util/compileBooleanMatcher");
15const { chunkHasCss } = require("./CssModulesPlugin");
16
17/** @typedef {import("../Chunk")} Chunk */
18/** @typedef {import("../Chunk").ChunkId} ChunkId */
19/** @typedef {import("../ChunkGraph")} ChunkGraph */
20/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
21
22/**
23 * @typedef {object} CssLoadingRuntimeModulePluginHooks
24 * @property {SyncWaterfallHook<[string, Chunk]>} createStylesheet
25 * @property {SyncWaterfallHook<[string, Chunk]>} linkPreload
26 * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch
27 * @property {SyncWaterfallHook<[string, Chunk]>} linkInsert
28 */
29
30/** @type {WeakMap<Compilation, CssLoadingRuntimeModulePluginHooks>} */
31const compilationHooksMap = new WeakMap();
32
33class CssLoadingRuntimeModule extends RuntimeModule {
34 /**
35 * @param {Compilation} compilation the compilation
36 * @returns {CssLoadingRuntimeModulePluginHooks} hooks
37 */
38 static getCompilationHooks(compilation) {
39 if (!(compilation instanceof Compilation)) {
40 throw new TypeError(
41 "The 'compilation' argument must be an instance of Compilation"
42 );
43 }
44 let hooks = compilationHooksMap.get(compilation);
45 if (hooks === undefined) {
46 hooks = {
47 createStylesheet: new SyncWaterfallHook(["source", "chunk"]),
48 linkPreload: new SyncWaterfallHook(["source", "chunk"]),
49 linkPrefetch: new SyncWaterfallHook(["source", "chunk"]),
50 linkInsert: new SyncWaterfallHook(["source", "chunk"])
51 };
52 compilationHooksMap.set(compilation, hooks);
53 }
54 return hooks;
55 }
56
57 /**
58 * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements
59 */
60 constructor(runtimeRequirements) {
61 super("css loading", 10);
62
63 this._runtimeRequirements = runtimeRequirements;
64 }
65
66 /**
67 * Generates runtime code for this runtime module.
68 * @returns {string | null} runtime code
69 */
70 generate() {
71 const { _runtimeRequirements } = this;
72 const compilation = /** @type {Compilation} */ (this.compilation);
73 const chunk = /** @type {Chunk} */ (this.chunk);
74 const {
75 chunkGraph,
76 runtimeTemplate,
77 outputOptions: {
78 crossOriginLoading,
79 uniqueName,
80 chunkLoadTimeout: loadTimeout,
81 charset
82 }
83 } = compilation;
84 const fn = RuntimeGlobals.ensureChunkHandlers;
85 const conditionMap = chunkGraph.getChunkConditionMap(
86 chunk,
87 /**
88 * @param {Chunk} chunk the chunk
89 * @param {ChunkGraph} chunkGraph the chunk graph
90 * @returns {boolean} true, if the chunk has css
91 */
92 (chunk, chunkGraph) =>
93 Boolean(chunkGraph.getChunkModulesIterableBySourceType(chunk, CSS_TYPE))
94 );
95 const hasCssMatcher = compileBooleanMatcher(conditionMap);
96
97 const withLoading =
98 _runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) &&
99 hasCssMatcher !== false;
100 /** @type {boolean} */
101 const withHmr = _runtimeRequirements.has(
102 RuntimeGlobals.hmrDownloadUpdateHandlers
103 );
104 /** @type {Set<ChunkId>} */
105 const initialChunkIds = new Set();
106 for (const c of chunk.getAllInitialChunks()) {
107 if (chunkHasCss(c, chunkGraph)) {
108 initialChunkIds.add(/** @type {ChunkId} */ (c.id));
109 }
110 }
111
112 if (!withLoading && !withHmr) {
113 return null;
114 }
115
116 const environment = compilation.outputOptions.environment;
117 const isNeutralPlatform = runtimeTemplate.isNeutralPlatform();
118 const withPrefetch =
119 this._runtimeRequirements.has(RuntimeGlobals.prefetchChunkHandlers) &&
120 (environment.document || isNeutralPlatform) &&
121 chunk.hasChildByOrder(chunkGraph, "prefetch", true, chunkHasCss);
122 const withPreload =
123 this._runtimeRequirements.has(RuntimeGlobals.preloadChunkHandlers) &&
124 (environment.document || isNeutralPlatform) &&
125 chunk.hasChildByOrder(chunkGraph, "preload", true, chunkHasCss);
126
127 const { linkPreload, linkPrefetch, createStylesheet, linkInsert } =
128 CssLoadingRuntimeModule.getCompilationHooks(compilation);
129
130 const withFetchPriority = _runtimeRequirements.has(
131 RuntimeGlobals.hasFetchPriority
132 );
133
134 const stateExpression = withHmr
135 ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_css`
136 : undefined;
137
138 const code = Template.asString([
139 "link = document.createElement('link');",
140 charset ? "link.charset = 'utf-8';" : "",
141 `if (${RuntimeGlobals.scriptNonce}) {`,
142 Template.indent(
143 `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
144 ),
145 "}",
146 uniqueName
147 ? 'link.setAttribute("data-webpack", uniqueName + ":" + key);'
148 : "",
149 withFetchPriority
150 ? Template.asString([
151 "if(fetchPriority) {",
152 Template.indent(
153 'link.setAttribute("fetchpriority", fetchPriority);'
154 ),
155 "}"
156 ])
157 : "",
158 "link.setAttribute(loadingAttribute, 1);",
159 'link.rel = "stylesheet";',
160 "link.href = url;",
161 crossOriginLoading
162 ? crossOriginLoading === "use-credentials"
163 ? 'link.crossOrigin = "use-credentials";'
164 : Template.asString([
165 "if (link.href.indexOf(window.location.origin + '/') !== 0) {",
166 Template.indent(
167 `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};`
168 ),
169 "}"
170 ])
171 : ""
172 ]);
173
174 return Template.asString([
175 "// object to store loaded and loading chunks",
176 "// undefined = chunk not loaded, null = chunk preloaded/prefetched",
177 "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded",
178 `var installedChunks = ${
179 stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
180 }{`,
181 Template.indent(
182 Array.from(initialChunkIds, (id) => `${JSON.stringify(id)}: 0`).join(
183 ",\n"
184 )
185 ),
186 "};",
187 "",
188 uniqueName
189 ? `var uniqueName = ${JSON.stringify(
190 runtimeTemplate.outputOptions.uniqueName
191 )};`
192 : "// data-webpack is not used as build has no uniqueName",
193 withLoading || withHmr
194 ? Template.asString([
195 'var loadingAttribute = "data-webpack-loading";',
196 `var loadStylesheet = ${runtimeTemplate.basicFunction(
197 `chunkId, url, done${
198 withFetchPriority ? ", fetchPriority" : ""
199 }${withHmr ? ", hmr" : ""}`,
200 [
201 'var link, needAttach, key = "chunk-" + chunkId;',
202 withHmr ? "if(!hmr) {" : "",
203 'var links = document.getElementsByTagName("link");',
204 "for(var i = 0; i < links.length; i++) {",
205 Template.indent([
206 "var l = links[i];",
207 `if(l.rel == "stylesheet" && (${
208 withHmr
209 ? 'l.href.startsWith(url) || l.getAttribute("href").startsWith(url)'
210 : 'l.href == url || l.getAttribute("href") == url'
211 }${
212 uniqueName
213 ? ' || l.getAttribute("data-webpack") == uniqueName + ":" + key'
214 : ""
215 })) { link = l; break; }`
216 ]),
217 "}",
218 "if(!done) return link;",
219 withHmr ? "}" : "",
220 "if(!link) {",
221 Template.indent([
222 "needAttach = true;",
223 createStylesheet.call(code, /** @type {Chunk} */ (this.chunk))
224 ]),
225 "}",
226 `var onLinkComplete = ${runtimeTemplate.basicFunction(
227 "prev, event",
228 Template.asString([
229 "link.onerror = link.onload = null;",
230 "link.removeAttribute(loadingAttribute);",
231 "clearTimeout(timeout);",
232 'if(event && event.type != "load") link.parentNode.removeChild(link)',
233 "done(event);",
234 "if(prev) return prev(event);"
235 ])
236 )};`,
237 "if(link.getAttribute(loadingAttribute)) {",
238 Template.indent([
239 `var timeout = setTimeout(onLinkComplete.bind(null, undefined, { type: 'timeout', target: link }), ${loadTimeout});`,
240 "link.onerror = onLinkComplete.bind(null, link.onerror);",
241 "link.onload = onLinkComplete.bind(null, link.onload);"
242 ]),
243 "} else onLinkComplete(undefined, { type: 'load', target: link });", // We assume any existing stylesheet is render blocking
244 withHmr && withFetchPriority
245 ? 'if (hmr && hmr.getAttribute("fetchpriority")) link.setAttribute("fetchpriority", hmr.getAttribute("fetchpriority"));'
246 : "",
247 linkInsert.call(
248 withHmr
249 ? Template.asString([
250 "if (hmr) {",
251 Template.indent(
252 "hmr.parentNode.insertBefore(link, hmr);"
253 ),
254 "} else if (needAttach) {",
255 Template.indent("document.head.appendChild(link);"),
256 "}"
257 ])
258 : Template.asString([
259 "if (needAttach) {",
260 Template.indent("document.head.appendChild(link);"),
261 "}"
262 ]),
263 /** @type {Chunk} */ (this.chunk)
264 ),
265 "return link;"
266 ]
267 )};`
268 ])
269 : "",
270 withLoading
271 ? Template.asString([
272 `${fn}.css = ${runtimeTemplate.basicFunction(
273 `chunkId, promises${withFetchPriority ? " , fetchPriority" : ""}`,
274 [
275 "// css chunk loading",
276 `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`,
277 'if(installedChunkData !== 0) { // 0 means "already installed".',
278 Template.indent([
279 "",
280 '// a Promise means "currently loading".',
281 "if(installedChunkData) {",
282 Template.indent(["promises.push(installedChunkData[2]);"]),
283 "} else {",
284 Template.indent([
285 hasCssMatcher === true
286 ? "if(true) { // all chunks have CSS"
287 : `if(${hasCssMatcher("chunkId")}) {`,
288 Template.indent([
289 "// setup Promise in chunk cache",
290 `var promise = new Promise(${runtimeTemplate.expressionFunction(
291 "installedChunkData = installedChunks[chunkId] = [resolve, reject]",
292 "resolve, reject"
293 )});`,
294 "promises.push(installedChunkData[2] = promise);",
295 "",
296 "// start chunk loading",
297 `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`,
298 "// create error before stack unwound to get useful stacktrace later",
299 "var error = new Error();",
300 `var loadingEnded = ${runtimeTemplate.basicFunction(
301 "event",
302 [
303 `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId)) {`,
304 Template.indent([
305 "installedChunkData = installedChunks[chunkId];",
306 "if(installedChunkData !== 0) installedChunks[chunkId] = undefined;",
307 "if(installedChunkData) {",
308 Template.indent([
309 'if(event.type !== "load") {',
310 Template.indent([
311 "var errorType = event && event.type;",
312 "var realHref = event && event.target && event.target.href;",
313 "error.message = 'Loading css chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realHref + ')';",
314 "error.name = 'ChunkLoadError';",
315 "error.type = errorType;",
316 "error.request = realHref;",
317 "installedChunkData[1](error);"
318 ]),
319 "} else {",
320 Template.indent([
321 "installedChunks[chunkId] = 0;",
322 "installedChunkData[0]();"
323 ]),
324 "}"
325 ]),
326 "}"
327 ]),
328 "}"
329 ]
330 )};`,
331 isNeutralPlatform
332 ? "if (typeof document !== 'undefined') {"
333 : "",
334 Template.indent([
335 `loadStylesheet(chunkId, url, loadingEnded${
336 withFetchPriority ? ", fetchPriority" : ""
337 });`
338 ]),
339 isNeutralPlatform
340 ? "} else { loadingEnded({ type: 'load' }); }"
341 : ""
342 ]),
343 "} else installedChunks[chunkId] = 0;"
344 ]),
345 "}"
346 ]),
347 "}"
348 ]
349 )};`
350 ])
351 : "// no chunk loading",
352 "",
353 withPrefetch && hasCssMatcher !== false
354 ? `${
355 RuntimeGlobals.prefetchChunkHandlers
356 }.s = ${runtimeTemplate.basicFunction("chunkId", [
357 `if((!${
358 RuntimeGlobals.hasOwnProperty
359 }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${
360 hasCssMatcher === true ? "true" : hasCssMatcher("chunkId")
361 }) {`,
362 Template.indent([
363 "installedChunks[chunkId] = null;",
364 isNeutralPlatform
365 ? "if (typeof document === 'undefined') return;"
366 : "",
367 linkPrefetch.call(
368 Template.asString([
369 "var link = document.createElement('link');",
370 charset ? "link.charset = 'utf-8';" : "",
371 crossOriginLoading
372 ? `link.crossOrigin = ${JSON.stringify(
373 crossOriginLoading
374 )};`
375 : "",
376 `if (${RuntimeGlobals.scriptNonce}) {`,
377 Template.indent(
378 `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
379 ),
380 "}",
381 'link.rel = "prefetch";',
382 'link.as = "style";',
383 `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`
384 ]),
385 chunk
386 ),
387 "document.head.appendChild(link);"
388 ]),
389 "}"
390 ])};`
391 : "// no prefetching",
392 "",
393 withPreload && hasCssMatcher !== false
394 ? `${
395 RuntimeGlobals.preloadChunkHandlers
396 }.s = ${runtimeTemplate.basicFunction("chunkId", [
397 `if((!${
398 RuntimeGlobals.hasOwnProperty
399 }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${
400 hasCssMatcher === true ? "true" : hasCssMatcher("chunkId")
401 }) {`,
402 Template.indent([
403 "installedChunks[chunkId] = null;",
404 isNeutralPlatform
405 ? "if (typeof document === 'undefined') return;"
406 : "",
407 linkPreload.call(
408 Template.asString([
409 "var link = document.createElement('link');",
410 charset ? "link.charset = 'utf-8';" : "",
411 `if (${RuntimeGlobals.scriptNonce}) {`,
412 Template.indent(
413 `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
414 ),
415 "}",
416 'link.rel = "preload";',
417 'link.as = "style";',
418 `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`,
419 crossOriginLoading
420 ? crossOriginLoading === "use-credentials"
421 ? 'link.crossOrigin = "use-credentials";'
422 : Template.asString([
423 "if (link.href.indexOf(window.location.origin + '/') !== 0) {",
424 Template.indent(
425 `link.crossOrigin = ${JSON.stringify(
426 crossOriginLoading
427 )};`
428 ),
429 "}"
430 ])
431 : ""
432 ]),
433 chunk
434 ),
435 "document.head.appendChild(link);"
436 ]),
437 "}"
438 ])};`
439 : "// no preloaded",
440 withHmr
441 ? Template.asString([
442 "var oldTags = [];",
443 "var newTags = [];",
444 `var applyHandler = ${runtimeTemplate.basicFunction("options", [
445 `return { dispose: ${runtimeTemplate.basicFunction("", [
446 "while(oldTags.length) {",
447 Template.indent([
448 "var oldTag = oldTags.pop();",
449 "if(oldTag && oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);"
450 ]),
451 "}"
452 ])}, apply: ${runtimeTemplate.basicFunction("", [
453 "while(newTags.length) {",
454 Template.indent([
455 "var newTag = newTags.pop();",
456 "newTag.sheet.disabled = false"
457 ]),
458 "}"
459 ])} };`
460 ])}`,
461 `var cssTextKey = ${runtimeTemplate.returningFunction(
462 `Array.from(link.sheet.cssRules, ${runtimeTemplate.returningFunction(
463 "r.cssText",
464 "r"
465 )}).join()`,
466 "link"
467 )};`,
468 `${
469 RuntimeGlobals.hmrDownloadUpdateHandlers
470 }.css = ${runtimeTemplate.basicFunction(
471 "chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList, css",
472 [
473 isNeutralPlatform
474 ? "if (typeof document === 'undefined') return;"
475 : "",
476 "applyHandlers.push(applyHandler);",
477 "// Read CSS removed chunks from update manifest",
478 "var cssRemovedChunks = css && css.r;",
479 `chunkIds.forEach(${runtimeTemplate.basicFunction("chunkId", [
480 `var filename = ${RuntimeGlobals.getChunkCssFilename}(chunkId);`,
481 `var url = ${RuntimeGlobals.publicPath} + filename;`,
482 "var oldTag = loadStylesheet(chunkId, url);",
483 `if(!oldTag && !${withHmr} ) return;`,
484 "// Skip if CSS was removed",
485 "if(cssRemovedChunks && cssRemovedChunks.indexOf(chunkId) >= 0) {",
486 Template.indent(["oldTags.push(oldTag);", "return;"]),
487 "}",
488 "",
489 "// create error before stack unwound to get useful stacktrace later",
490 "var error = new Error();",
491 `promises.push(new Promise(${runtimeTemplate.basicFunction(
492 "resolve, reject",
493 [
494 `var link = loadStylesheet(chunkId, url + (url.indexOf("?") < 0 ? "?" : "&") + "hmr=" + Date.now(), ${runtimeTemplate.basicFunction(
495 "event",
496 [
497 'if(event.type !== "load") {',
498 Template.indent([
499 "var errorType = event && event.type;",
500 "var realHref = event && event.target && event.target.href;",
501 "error.message = 'Loading css hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realHref + ')';",
502 "error.name = 'ChunkLoadError';",
503 "error.type = errorType;",
504 "error.request = realHref;",
505 "reject(error);"
506 ]),
507 "} else {",
508 Template.indent([
509 "try { if(cssTextKey(oldTag) == cssTextKey(link)) { if(link.parentNode) link.parentNode.removeChild(link); return resolve(); } } catch(e) {}",
510 "link.sheet.disabled = true;",
511 "oldTags.push(oldTag);",
512 "newTags.push(link);",
513 "resolve();"
514 ]),
515 "}"
516 ]
517 )}, ${withFetchPriority ? "undefined," : ""} oldTag);`
518 ]
519 )}));`
520 ])});`
521 ]
522 )}`
523 ])
524 : "// no hmr"
525 ]);
526 }
527}
528
529module.exports = CssLoadingRuntimeModule;
Note: See TracBrowser for help on using the repository browser.