JsonpChunkLoadingRuntimeModule.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. const { SyncWaterfallHook } = require("tapable");
  6. const Compilation = require("../Compilation");
  7. const RuntimeGlobals = require("../RuntimeGlobals");
  8. const RuntimeModule = require("../RuntimeModule");
  9. const Template = require("../Template");
  10. const {
  11. generateJavascriptHMR
  12. } = require("../hmr/JavascriptHotModuleReplacementHelper");
  13. const chunkHasJs = require("../javascript/JavascriptModulesPlugin").chunkHasJs;
  14. const { getInitialChunkIds } = require("../javascript/StartupHelpers");
  15. const compileBooleanMatcher = require("../util/compileBooleanMatcher");
  16. /** @typedef {import("../Chunk")} Chunk */
  17. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  18. /** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
  19. /**
  20. * @typedef {object} JsonpCompilationPluginHooks
  21. * @property {SyncWaterfallHook<[string, Chunk]>} linkPreload
  22. * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch
  23. */
  24. /** @type {WeakMap<Compilation, JsonpCompilationPluginHooks>} */
  25. const compilationHooksMap = new WeakMap();
  26. class JsonpChunkLoadingRuntimeModule extends RuntimeModule {
  27. /**
  28. * @param {Compilation} compilation the compilation
  29. * @returns {JsonpCompilationPluginHooks} 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. linkPreload: new SyncWaterfallHook(["source", "chunk"]),
  41. linkPrefetch: new SyncWaterfallHook(["source", "chunk"])
  42. };
  43. compilationHooksMap.set(compilation, hooks);
  44. }
  45. return hooks;
  46. }
  47. /**
  48. * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements
  49. */
  50. constructor(runtimeRequirements) {
  51. super("jsonp chunk loading", RuntimeModule.STAGE_ATTACH);
  52. /** @type {ReadOnlyRuntimeRequirements} */
  53. this._runtimeRequirements = runtimeRequirements;
  54. }
  55. /**
  56. * @private
  57. * @param {Chunk} chunk chunk
  58. * @returns {string} generated code
  59. */
  60. _generateBaseUri(chunk) {
  61. const options = chunk.getEntryOptions();
  62. if (options && options.baseUri) {
  63. return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`;
  64. }
  65. return `${RuntimeGlobals.baseURI} = (typeof document !== 'undefined' && document.baseURI) || self.location.href;`;
  66. }
  67. /**
  68. * Generates runtime code for this runtime module.
  69. * @returns {string | null} runtime code
  70. */
  71. generate() {
  72. const compilation = /** @type {Compilation} */ (this.compilation);
  73. const {
  74. runtimeTemplate,
  75. outputOptions: {
  76. chunkLoadingGlobal,
  77. hotUpdateGlobal,
  78. crossOriginLoading,
  79. scriptType,
  80. charset
  81. }
  82. } = compilation;
  83. const globalObject = runtimeTemplate.globalObject;
  84. const { linkPreload, linkPrefetch } =
  85. JsonpChunkLoadingRuntimeModule.getCompilationHooks(compilation);
  86. const fn = RuntimeGlobals.ensureChunkHandlers;
  87. const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI);
  88. const withLoading = this._runtimeRequirements.has(
  89. RuntimeGlobals.ensureChunkHandlers
  90. );
  91. const withCallback = this._runtimeRequirements.has(
  92. RuntimeGlobals.chunkCallback
  93. );
  94. const withOnChunkLoad = this._runtimeRequirements.has(
  95. RuntimeGlobals.onChunksLoaded
  96. );
  97. const withHmr = this._runtimeRequirements.has(
  98. RuntimeGlobals.hmrDownloadUpdateHandlers
  99. );
  100. const withHmrManifest = this._runtimeRequirements.has(
  101. RuntimeGlobals.hmrDownloadManifest
  102. );
  103. const withFetchPriority = this._runtimeRequirements.has(
  104. RuntimeGlobals.hasFetchPriority
  105. );
  106. const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify(
  107. chunkLoadingGlobal
  108. )}]`;
  109. const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
  110. const chunk = /** @type {Chunk} */ (this.chunk);
  111. const withPrefetch =
  112. this._runtimeRequirements.has(RuntimeGlobals.prefetchChunkHandlers) &&
  113. chunk.hasChildByOrder(chunkGraph, "prefetch", true, chunkHasJs);
  114. const withPreload =
  115. this._runtimeRequirements.has(RuntimeGlobals.preloadChunkHandlers) &&
  116. chunk.hasChildByOrder(chunkGraph, "preload", true, chunkHasJs);
  117. const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs);
  118. const hasJsMatcher = compileBooleanMatcher(conditionMap);
  119. const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs);
  120. const stateExpression = withHmr
  121. ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_jsonp`
  122. : undefined;
  123. return Template.asString([
  124. withBaseURI ? this._generateBaseUri(chunk) : "// no baseURI",
  125. "",
  126. "// object to store loaded and loading chunks",
  127. "// undefined = chunk not loaded, null = chunk preloaded/prefetched",
  128. "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded",
  129. `var installedChunks = ${
  130. stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
  131. }{`,
  132. Template.indent(
  133. Array.from(initialChunkIds, (id) => `${JSON.stringify(id)}: 0`).join(
  134. ",\n"
  135. )
  136. ),
  137. "};",
  138. "",
  139. withLoading
  140. ? Template.asString([
  141. `${fn}.j = ${runtimeTemplate.basicFunction(
  142. `chunkId, promises${withFetchPriority ? ", fetchPriority" : ""}`,
  143. hasJsMatcher !== false
  144. ? Template.indent([
  145. "// JSONP chunk loading for javascript",
  146. `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`,
  147. 'if(installedChunkData !== 0) { // 0 means "already installed".',
  148. Template.indent([
  149. "",
  150. '// a Promise means "currently loading".',
  151. "if(installedChunkData) {",
  152. Template.indent([
  153. "promises.push(installedChunkData[2]);"
  154. ]),
  155. "} else {",
  156. Template.indent([
  157. hasJsMatcher === true
  158. ? "if(true) { // all chunks have JS"
  159. : `if(${hasJsMatcher("chunkId")}) {`,
  160. Template.indent([
  161. "// setup Promise in chunk cache",
  162. `var promise = new Promise(${runtimeTemplate.expressionFunction(
  163. "installedChunkData = installedChunks[chunkId] = [resolve, reject]",
  164. "resolve, reject"
  165. )});`,
  166. "promises.push(installedChunkData[2] = promise);",
  167. "",
  168. "// start chunk loading",
  169. `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`,
  170. "// create error before stack unwound to get useful stacktrace later",
  171. "var error = new Error();",
  172. `var loadingEnded = ${runtimeTemplate.basicFunction(
  173. "event",
  174. [
  175. `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId)) {`,
  176. Template.indent([
  177. "installedChunkData = installedChunks[chunkId];",
  178. "if(installedChunkData !== 0) installedChunks[chunkId] = undefined;",
  179. "if(installedChunkData) {",
  180. Template.indent([
  181. "var errorType = event && (event.type === 'load' ? 'missing' : event.type);",
  182. "var realSrc = event && event.target && event.target.src;",
  183. "error.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';",
  184. "error.name = 'ChunkLoadError';",
  185. "error.type = errorType;",
  186. "error.request = realSrc;",
  187. "installedChunkData[1](error);"
  188. ]),
  189. "}"
  190. ]),
  191. "}"
  192. ]
  193. )};`,
  194. `${
  195. RuntimeGlobals.loadScript
  196. }(url, loadingEnded, "chunk-" + chunkId, chunkId${
  197. withFetchPriority ? ", fetchPriority" : ""
  198. });`
  199. ]),
  200. hasJsMatcher === true
  201. ? "}"
  202. : "} else installedChunks[chunkId] = 0;"
  203. ]),
  204. "}"
  205. ]),
  206. "}"
  207. ])
  208. : Template.indent(["installedChunks[chunkId] = 0;"])
  209. )};`
  210. ])
  211. : "// no chunk on demand loading",
  212. "",
  213. withPrefetch && hasJsMatcher !== false
  214. ? `${
  215. RuntimeGlobals.prefetchChunkHandlers
  216. }.j = ${runtimeTemplate.basicFunction("chunkId", [
  217. `if((!${
  218. RuntimeGlobals.hasOwnProperty
  219. }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${
  220. hasJsMatcher === true ? "true" : hasJsMatcher("chunkId")
  221. }) {`,
  222. Template.indent([
  223. "installedChunks[chunkId] = null;",
  224. linkPrefetch.call(
  225. Template.asString([
  226. "var link = document.createElement('link');",
  227. charset ? "link.charset = 'utf-8';" : "",
  228. crossOriginLoading
  229. ? `link.crossOrigin = ${JSON.stringify(
  230. crossOriginLoading
  231. )};`
  232. : "",
  233. `if (${RuntimeGlobals.scriptNonce}) {`,
  234. Template.indent(
  235. `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
  236. ),
  237. "}",
  238. 'link.rel = "prefetch";',
  239. 'link.as = "script";',
  240. `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`
  241. ]),
  242. chunk
  243. ),
  244. "document.head.appendChild(link);"
  245. ]),
  246. "}"
  247. ])};`
  248. : "// no prefetching",
  249. "",
  250. withPreload && hasJsMatcher !== false
  251. ? `${
  252. RuntimeGlobals.preloadChunkHandlers
  253. }.j = ${runtimeTemplate.basicFunction("chunkId", [
  254. `if((!${
  255. RuntimeGlobals.hasOwnProperty
  256. }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${
  257. hasJsMatcher === true ? "true" : hasJsMatcher("chunkId")
  258. }) {`,
  259. Template.indent([
  260. "installedChunks[chunkId] = null;",
  261. linkPreload.call(
  262. Template.asString([
  263. "var link = document.createElement('link');",
  264. scriptType && scriptType !== "module"
  265. ? `link.type = ${JSON.stringify(scriptType)};`
  266. : "",
  267. charset ? "link.charset = 'utf-8';" : "",
  268. `if (${RuntimeGlobals.scriptNonce}) {`,
  269. Template.indent(
  270. `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
  271. ),
  272. "}",
  273. scriptType === "module"
  274. ? 'link.rel = "modulepreload";'
  275. : 'link.rel = "preload";',
  276. scriptType === "module" ? "" : 'link.as = "script";',
  277. `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`,
  278. crossOriginLoading
  279. ? crossOriginLoading === "use-credentials"
  280. ? 'link.crossOrigin = "use-credentials";'
  281. : Template.asString([
  282. "if (link.href.indexOf(window.location.origin + '/') !== 0) {",
  283. Template.indent(
  284. `link.crossOrigin = ${JSON.stringify(
  285. crossOriginLoading
  286. )};`
  287. ),
  288. "}"
  289. ])
  290. : ""
  291. ]),
  292. chunk
  293. ),
  294. "document.head.appendChild(link);"
  295. ]),
  296. "}"
  297. ])};`
  298. : "// no preloaded",
  299. "",
  300. withHmr
  301. ? Template.asString([
  302. "var currentUpdatedModulesList;",
  303. "var waitingUpdateResolves = {};",
  304. "function loadUpdateChunk(chunkId, updatedModulesList) {",
  305. Template.indent([
  306. "currentUpdatedModulesList = updatedModulesList;",
  307. `return new Promise(${runtimeTemplate.basicFunction(
  308. "resolve, reject",
  309. [
  310. "waitingUpdateResolves[chunkId] = resolve;",
  311. "// start update chunk loading",
  312. `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId);`,
  313. "// create error before stack unwound to get useful stacktrace later",
  314. "var error = new Error();",
  315. `var loadingEnded = ${runtimeTemplate.basicFunction("event", [
  316. "if(waitingUpdateResolves[chunkId]) {",
  317. Template.indent([
  318. "waitingUpdateResolves[chunkId] = undefined",
  319. "var errorType = event && (event.type === 'load' ? 'missing' : event.type);",
  320. "var realSrc = event && event.target && event.target.src;",
  321. "error.message = 'Loading hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';",
  322. "error.name = 'ChunkLoadError';",
  323. "error.type = errorType;",
  324. "error.request = realSrc;",
  325. "reject(error);"
  326. ]),
  327. "}"
  328. ])};`,
  329. `${RuntimeGlobals.loadScript}(url, loadingEnded);`
  330. ]
  331. )});`
  332. ]),
  333. "}",
  334. "",
  335. `${globalObject}[${JSON.stringify(
  336. hotUpdateGlobal
  337. )}] = ${runtimeTemplate.basicFunction(
  338. "chunkId, moreModules, runtime",
  339. [
  340. "for(var moduleId in moreModules) {",
  341. Template.indent([
  342. `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
  343. Template.indent([
  344. "currentUpdate[moduleId] = moreModules[moduleId];",
  345. "if(currentUpdatedModulesList) currentUpdatedModulesList.push(moduleId);"
  346. ]),
  347. "}"
  348. ]),
  349. "}",
  350. "if(runtime) currentUpdateRuntime.push(runtime);",
  351. "if(waitingUpdateResolves[chunkId]) {",
  352. Template.indent([
  353. "waitingUpdateResolves[chunkId]();",
  354. "waitingUpdateResolves[chunkId] = undefined;"
  355. ]),
  356. "}"
  357. ]
  358. )};`,
  359. "",
  360. generateJavascriptHMR("jsonp")
  361. ])
  362. : "// no HMR",
  363. "",
  364. withHmrManifest
  365. ? Template.asString([
  366. `${
  367. RuntimeGlobals.hmrDownloadManifest
  368. } = ${runtimeTemplate.basicFunction("", [
  369. 'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");',
  370. `return fetch(${RuntimeGlobals.publicPath} + ${
  371. RuntimeGlobals.getUpdateManifestFilename
  372. }()).then(${runtimeTemplate.basicFunction("response", [
  373. "if(response.status === 404) return; // no update available",
  374. 'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);',
  375. "return response.json();"
  376. ])});`
  377. ])};`
  378. ])
  379. : "// no HMR manifest",
  380. "",
  381. withOnChunkLoad
  382. ? `${
  383. RuntimeGlobals.onChunksLoaded
  384. }.j = ${runtimeTemplate.returningFunction(
  385. "installedChunks[chunkId] === 0",
  386. "chunkId"
  387. )};`
  388. : "// no on chunks loaded",
  389. "",
  390. withCallback || withLoading
  391. ? Template.asString([
  392. "// install a JSONP callback for chunk loading",
  393. `var webpackJsonpCallback = ${runtimeTemplate.basicFunction(
  394. "parentChunkLoadingFunction, data",
  395. [
  396. runtimeTemplate.destructureArray(
  397. ["chunkIds", "moreModules", "runtime"],
  398. "data"
  399. ),
  400. '// add "moreModules" to the modules object,',
  401. '// then flag all "chunkIds" as loaded and fire callback',
  402. "var moduleId, chunkId, i = 0;",
  403. `if(chunkIds.some(${runtimeTemplate.returningFunction(
  404. "installedChunks[id] !== 0",
  405. "id"
  406. )})) {`,
  407. Template.indent([
  408. "for(moduleId in moreModules) {",
  409. Template.indent([
  410. `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
  411. Template.indent(
  412. `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];`
  413. ),
  414. "}"
  415. ]),
  416. "}",
  417. `if(runtime) var result = runtime(${RuntimeGlobals.require});`
  418. ]),
  419. "}",
  420. "if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);",
  421. "for(;i < chunkIds.length; i++) {",
  422. Template.indent([
  423. "chunkId = chunkIds[i];",
  424. `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`,
  425. Template.indent("installedChunks[chunkId][0]();"),
  426. "}",
  427. "installedChunks[chunkId] = 0;"
  428. ]),
  429. "}",
  430. withOnChunkLoad
  431. ? `return ${RuntimeGlobals.onChunksLoaded}(result);`
  432. : ""
  433. ]
  434. )}`,
  435. "",
  436. `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`,
  437. "chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));",
  438. "chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));"
  439. ])
  440. : "// no jsonp function"
  441. ]);
  442. }
  443. }
  444. module.exports = JsonpChunkLoadingRuntimeModule;