CssLoadingRuntimeModule.js 17 KB

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