JsonpChunkLoadingRuntimeModule.js 16 KB

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