JsonpChunkLoadingRuntimeModule.js 16 KB

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