CssLoadingRuntimeModule.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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 { CSS_TYPE } = require("../ModuleSourceTypeConstants");
  9. const RuntimeGlobals = require("../RuntimeGlobals");
  10. const RuntimeModule = require("../RuntimeModule");
  11. const Template = require("../Template");
  12. const compileBooleanMatcher = require("../util/compileBooleanMatcher");
  13. const { chunkHasCss } = require("./CssModulesPlugin");
  14. /** @typedef {import("../Chunk")} Chunk */
  15. /** @typedef {import("../Chunk").ChunkId} ChunkId */
  16. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  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. charset
  70. }
  71. } = compilation;
  72. const fn = RuntimeGlobals.ensureChunkHandlers;
  73. const conditionMap = chunkGraph.getChunkConditionMap(
  74. chunk,
  75. /**
  76. * @param {Chunk} chunk the chunk
  77. * @param {ChunkGraph} chunkGraph the chunk graph
  78. * @returns {boolean} true, if the chunk has css
  79. */
  80. (chunk, chunkGraph) =>
  81. Boolean(chunkGraph.getChunkModulesIterableBySourceType(chunk, CSS_TYPE))
  82. );
  83. const hasCssMatcher = compileBooleanMatcher(conditionMap);
  84. const withLoading =
  85. _runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) &&
  86. hasCssMatcher !== false;
  87. /** @type {boolean} */
  88. const withHmr = _runtimeRequirements.has(
  89. RuntimeGlobals.hmrDownloadUpdateHandlers
  90. );
  91. /** @type {Set<ChunkId>} */
  92. const initialChunkIds = new Set();
  93. for (const c of chunk.getAllInitialChunks()) {
  94. if (chunkHasCss(c, chunkGraph)) {
  95. initialChunkIds.add(/** @type {ChunkId} */ (c.id));
  96. }
  97. }
  98. if (!withLoading && !withHmr) {
  99. return null;
  100. }
  101. const environment = compilation.outputOptions.environment;
  102. const isNeutralPlatform = runtimeTemplate.isNeutralPlatform();
  103. const withPrefetch =
  104. this._runtimeRequirements.has(RuntimeGlobals.prefetchChunkHandlers) &&
  105. (environment.document || isNeutralPlatform) &&
  106. chunk.hasChildByOrder(chunkGraph, "prefetch", true, chunkHasCss);
  107. const withPreload =
  108. this._runtimeRequirements.has(RuntimeGlobals.preloadChunkHandlers) &&
  109. (environment.document || isNeutralPlatform) &&
  110. chunk.hasChildByOrder(chunkGraph, "preload", true, chunkHasCss);
  111. const { linkPreload, linkPrefetch } =
  112. CssLoadingRuntimeModule.getCompilationHooks(compilation);
  113. const withFetchPriority = _runtimeRequirements.has(
  114. RuntimeGlobals.hasFetchPriority
  115. );
  116. const { createStylesheet } =
  117. CssLoadingRuntimeModule.getCompilationHooks(compilation);
  118. const stateExpression = withHmr
  119. ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_css`
  120. : undefined;
  121. const code = Template.asString([
  122. "link = document.createElement('link');",
  123. charset ? "link.charset = 'utf-8';" : "",
  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. charset ? "link.charset = 'utf-8';" : "",
  337. crossOriginLoading
  338. ? `link.crossOrigin = ${JSON.stringify(
  339. crossOriginLoading
  340. )};`
  341. : "",
  342. `if (${RuntimeGlobals.scriptNonce}) {`,
  343. Template.indent(
  344. `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
  345. ),
  346. "}",
  347. 'link.rel = "prefetch";',
  348. 'link.as = "style";',
  349. `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`
  350. ]),
  351. chunk
  352. ),
  353. "document.head.appendChild(link);"
  354. ]),
  355. "}"
  356. ])};`
  357. : "// no prefetching",
  358. "",
  359. withPreload && hasCssMatcher !== false
  360. ? `${
  361. RuntimeGlobals.preloadChunkHandlers
  362. }.s = ${runtimeTemplate.basicFunction("chunkId", [
  363. `if((!${
  364. RuntimeGlobals.hasOwnProperty
  365. }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${
  366. hasCssMatcher === true ? "true" : hasCssMatcher("chunkId")
  367. }) {`,
  368. Template.indent([
  369. "installedChunks[chunkId] = null;",
  370. isNeutralPlatform
  371. ? "if (typeof document === 'undefined') return;"
  372. : "",
  373. linkPreload.call(
  374. Template.asString([
  375. "var link = document.createElement('link');",
  376. charset ? "link.charset = 'utf-8';" : "",
  377. `if (${RuntimeGlobals.scriptNonce}) {`,
  378. Template.indent(
  379. `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
  380. ),
  381. "}",
  382. 'link.rel = "preload";',
  383. 'link.as = "style";',
  384. `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`,
  385. crossOriginLoading
  386. ? crossOriginLoading === "use-credentials"
  387. ? 'link.crossOrigin = "use-credentials";'
  388. : Template.asString([
  389. "if (link.href.indexOf(window.location.origin + '/') !== 0) {",
  390. Template.indent(
  391. `link.crossOrigin = ${JSON.stringify(
  392. crossOriginLoading
  393. )};`
  394. ),
  395. "}"
  396. ])
  397. : ""
  398. ]),
  399. chunk
  400. ),
  401. "document.head.appendChild(link);"
  402. ]),
  403. "}"
  404. ])};`
  405. : "// no preloaded",
  406. withHmr
  407. ? Template.asString([
  408. "var oldTags = [];",
  409. "var newTags = [];",
  410. `var applyHandler = ${runtimeTemplate.basicFunction("options", [
  411. `return { dispose: ${runtimeTemplate.basicFunction("", [
  412. "while(oldTags.length) {",
  413. Template.indent([
  414. "var oldTag = oldTags.pop();",
  415. "if(oldTag && oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);"
  416. ]),
  417. "}"
  418. ])}, apply: ${runtimeTemplate.basicFunction("", [
  419. "while(newTags.length) {",
  420. Template.indent([
  421. "var newTag = newTags.pop();",
  422. "newTag.sheet.disabled = false"
  423. ]),
  424. "}"
  425. ])} };`
  426. ])}`,
  427. `var cssTextKey = ${runtimeTemplate.returningFunction(
  428. `Array.from(link.sheet.cssRules, ${runtimeTemplate.returningFunction(
  429. "r.cssText",
  430. "r"
  431. )}).join()`,
  432. "link"
  433. )};`,
  434. `${
  435. RuntimeGlobals.hmrDownloadUpdateHandlers
  436. }.css = ${runtimeTemplate.basicFunction(
  437. "chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList, css",
  438. [
  439. isNeutralPlatform
  440. ? "if (typeof document === 'undefined') return;"
  441. : "",
  442. "applyHandlers.push(applyHandler);",
  443. "// Read CSS removed chunks from update manifest",
  444. "var cssRemovedChunks = css && css.r;",
  445. `chunkIds.forEach(${runtimeTemplate.basicFunction("chunkId", [
  446. `var filename = ${RuntimeGlobals.getChunkCssFilename}(chunkId);`,
  447. `var url = ${RuntimeGlobals.publicPath} + filename;`,
  448. "var oldTag = loadStylesheet(chunkId, url);",
  449. `if(!oldTag && !${withHmr} ) return;`,
  450. "// Skip if CSS was removed",
  451. "if(cssRemovedChunks && cssRemovedChunks.indexOf(chunkId) >= 0) {",
  452. Template.indent(["oldTags.push(oldTag);", "return;"]),
  453. "}",
  454. "",
  455. "// create error before stack unwound to get useful stacktrace later",
  456. "var error = new Error();",
  457. `promises.push(new Promise(${runtimeTemplate.basicFunction(
  458. "resolve, reject",
  459. [
  460. `var link = loadStylesheet(chunkId, url + (url.indexOf("?") < 0 ? "?" : "&") + "hmr=" + Date.now(), ${runtimeTemplate.basicFunction(
  461. "event",
  462. [
  463. 'if(event.type !== "load") {',
  464. Template.indent([
  465. "var errorType = event && event.type;",
  466. "var realHref = event && event.target && event.target.href;",
  467. "error.message = 'Loading css hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realHref + ')';",
  468. "error.name = 'ChunkLoadError';",
  469. "error.type = errorType;",
  470. "error.request = realHref;",
  471. "reject(error);"
  472. ]),
  473. "} else {",
  474. Template.indent([
  475. "try { if(cssTextKey(oldTag) == cssTextKey(link)) { if(link.parentNode) link.parentNode.removeChild(link); return resolve(); } } catch(e) {}",
  476. "link.sheet.disabled = true;",
  477. "oldTags.push(oldTag);",
  478. "newTags.push(link);",
  479. "resolve();"
  480. ]),
  481. "}"
  482. ]
  483. )}, ${withFetchPriority ? "undefined," : ""} oldTag);`
  484. ]
  485. )}));`
  486. ])});`
  487. ]
  488. )}`
  489. ])
  490. : "// no hmr"
  491. ]);
  492. }
  493. }
  494. module.exports = CssLoadingRuntimeModule;