CssLoadingRuntimeModule.js 5.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. "use strict";
  2. var _webpack = require("webpack");
  3. var _utils = require("./utils");
  4. const {
  5. comparators: {
  6. compareModulesByIdentifier
  7. }
  8. } = _webpack.util;
  9. const getCssChunkObject = (mainChunk, compilation) => {
  10. const obj = {};
  11. const {
  12. chunkGraph
  13. } = compilation;
  14. for (const chunk of mainChunk.getAllAsyncChunks()) {
  15. const modules = chunkGraph.getOrderedChunkModulesIterable(chunk, compareModulesByIdentifier);
  16. for (const module of modules) {
  17. if (module.type === _utils.MODULE_TYPE) {
  18. obj[chunk.id] = 1;
  19. break;
  20. }
  21. }
  22. }
  23. return obj;
  24. };
  25. module.exports = class CssLoadingRuntimeModule extends _webpack.RuntimeModule {
  26. constructor(runtimeRequirements) {
  27. super('css loading', 10);
  28. this.runtimeRequirements = runtimeRequirements;
  29. }
  30. generate() {
  31. const {
  32. chunk,
  33. compilation,
  34. runtimeRequirements
  35. } = this;
  36. const {
  37. runtimeTemplate,
  38. outputOptions: {
  39. crossOriginLoading
  40. }
  41. } = compilation;
  42. const chunkMap = getCssChunkObject(chunk, compilation);
  43. const withLoading = runtimeRequirements.has(_webpack.RuntimeGlobals.ensureChunkHandlers) && Object.keys(chunkMap).length > 0;
  44. const withHmr = runtimeRequirements.has(_webpack.RuntimeGlobals.hmrDownloadUpdateHandlers);
  45. if (!withLoading && !withHmr) return null;
  46. return _webpack.Template.asString([`var createStylesheet = ${runtimeTemplate.basicFunction('fullhref, resolve, reject', ['var linkTag = document.createElement("link");', 'linkTag.rel = "stylesheet";', 'linkTag.type = "text/css";', 'linkTag.onload = resolve;', 'linkTag.onerror = function(event) {', _webpack.Template.indent(['var request = event && event.target && event.target.src || fullhref;', 'var err = new Error("Loading CSS chunk " + chunkId + " failed.\\n(" + request + ")");', 'err.code = "CSS_CHUNK_LOAD_FAILED";', 'err.request = request;', 'linkTag.parentNode.removeChild(linkTag)', 'reject(err);']), '};', 'linkTag.href = fullhref;', crossOriginLoading ? _webpack.Template.asString([`if (linkTag.href.indexOf(window.location.origin + '/') !== 0) {`, _webpack.Template.indent(`linkTag.crossOrigin = ${JSON.stringify(crossOriginLoading)};`), '}']) : '', 'var head = document.getElementsByTagName("head")[0];', 'head.appendChild(linkTag);', 'return linkTag;'])};`, `var findStylesheet = ${runtimeTemplate.basicFunction('href, fullhref', ['var existingLinkTags = document.getElementsByTagName("link");', 'for(var i = 0; i < existingLinkTags.length; i++) {', _webpack.Template.indent(['var tag = existingLinkTags[i];', 'var dataHref = tag.getAttribute("data-href") || tag.getAttribute("href");', 'if(tag.rel === "stylesheet" && (dataHref === href || dataHref === fullhref)) return tag;']), '}', 'var existingStyleTags = document.getElementsByTagName("style");', 'for(var i = 0; i < existingStyleTags.length; i++) {', _webpack.Template.indent(['var tag = existingStyleTags[i];', 'var dataHref = tag.getAttribute("data-href");', 'if(dataHref === href || dataHref === fullhref) return tag;']), '}'])};`, `var loadStylesheet = ${runtimeTemplate.basicFunction('chunkId', `return new Promise(${runtimeTemplate.basicFunction('resolve, reject', [`var href = ${_webpack.RuntimeGlobals.require}.miniCssF(chunkId);`, `var fullhref = ${_webpack.RuntimeGlobals.publicPath} + href;`, 'if(findStylesheet(href, fullhref)) return resolve();', 'createStylesheet(fullhref, resolve, reject);'])});`)}`, withLoading ? _webpack.Template.asString(['// object to store loaded CSS chunks', 'var installedCssChunks = {', _webpack.Template.indent(chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(',\n')), '};', '', `${_webpack.RuntimeGlobals.ensureChunkHandlers}.miniCss = ${runtimeTemplate.basicFunction('chunkId, promises', [`var cssChunks = ${JSON.stringify(chunkMap)};`, 'if(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);', 'else if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {', _webpack.Template.indent([`promises.push(installedCssChunks[chunkId] = loadStylesheet(chunkId).then(${runtimeTemplate.basicFunction('', 'installedCssChunks[chunkId] = 0;')}, ${runtimeTemplate.basicFunction('e', ['delete installedCssChunks[chunkId];', 'throw e;'])}));`]), '}'])};`]) : '// no chunk loading', '', withHmr ? _webpack.Template.asString(['var oldTags = [];', 'var newTags = [];', `var applyHandler = ${runtimeTemplate.basicFunction('options', [`return { dispose: ${runtimeTemplate.basicFunction('', ['for(var i = 0; i < oldTags.length; i++) {', _webpack.Template.indent(['var oldTag = oldTags[i];', 'if(oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);']), '}', 'oldTags.length = 0;'])}, apply: ${runtimeTemplate.basicFunction('', ['for(var i = 0; i < newTags.length; i++) newTags[i].rel = "stylesheet";', 'newTags.length = 0;'])} };`])}`, `${_webpack.RuntimeGlobals.hmrDownloadUpdateHandlers}.miniCss = ${runtimeTemplate.basicFunction('chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList', ['applyHandlers.push(applyHandler);', `chunkIds.forEach(${runtimeTemplate.basicFunction('chunkId', [`var href = ${_webpack.RuntimeGlobals.require}.miniCssF(chunkId);`, `var fullhref = ${_webpack.RuntimeGlobals.publicPath} + href;`, 'const oldTag = findStylesheet(href, fullhref);', 'if(!oldTag) return;', `promises.push(new Promise(${runtimeTemplate.basicFunction('resolve, reject', [`var tag = createStylesheet(fullhref, ${runtimeTemplate.basicFunction('', ['tag.as = "style";', 'tag.rel = "preload";', 'resolve();'])}, reject);`, 'oldTags.push(oldTag);', 'newTags.push(tag);'])}));`])});`])}`]) : '// no hmr']);
  47. }
  48. };