JsonpChunkLoadingRuntimeModule.js 16 KB

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