JsonpChunkLoadingRuntimeModule.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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. }
  61. return `${RuntimeGlobals.baseURI} = document.baseURI || self.location.href;`;
  62. }
  63. /**
  64. * @returns {string | null} runtime code
  65. */
  66. generate() {
  67. const compilation = /** @type {Compilation} */ (this.compilation);
  68. const {
  69. runtimeTemplate,
  70. outputOptions: {
  71. chunkLoadingGlobal,
  72. hotUpdateGlobal,
  73. crossOriginLoading,
  74. scriptType,
  75. charset
  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 withFetchPriority = this._runtimeRequirements.has(
  99. RuntimeGlobals.hasFetchPriority
  100. );
  101. const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify(
  102. chunkLoadingGlobal
  103. )}]`;
  104. const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
  105. const chunk = /** @type {Chunk} */ (this.chunk);
  106. const withPrefetch =
  107. this._runtimeRequirements.has(RuntimeGlobals.prefetchChunkHandlers) &&
  108. chunk.hasChildByOrder(chunkGraph, "prefetch", true, chunkHasJs);
  109. const withPreload =
  110. this._runtimeRequirements.has(RuntimeGlobals.preloadChunkHandlers) &&
  111. chunk.hasChildByOrder(chunkGraph, "preload", true, chunkHasJs);
  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. charset ? "link.charset = 'utf-8';" : "",
  223. crossOriginLoading
  224. ? `link.crossOrigin = ${JSON.stringify(
  225. crossOriginLoading
  226. )};`
  227. : "",
  228. `if (${RuntimeGlobals.scriptNonce}) {`,
  229. Template.indent(
  230. `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
  231. ),
  232. "}",
  233. 'link.rel = "prefetch";',
  234. 'link.as = "script";',
  235. `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`
  236. ]),
  237. chunk
  238. ),
  239. "document.head.appendChild(link);"
  240. ]),
  241. "}"
  242. ])};`
  243. : "// no prefetching",
  244. "",
  245. withPreload && hasJsMatcher !== false
  246. ? `${
  247. RuntimeGlobals.preloadChunkHandlers
  248. }.j = ${runtimeTemplate.basicFunction("chunkId", [
  249. `if((!${
  250. RuntimeGlobals.hasOwnProperty
  251. }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${
  252. hasJsMatcher === true ? "true" : hasJsMatcher("chunkId")
  253. }) {`,
  254. Template.indent([
  255. "installedChunks[chunkId] = null;",
  256. linkPreload.call(
  257. Template.asString([
  258. "var link = document.createElement('link');",
  259. scriptType && scriptType !== "module"
  260. ? `link.type = ${JSON.stringify(scriptType)};`
  261. : "",
  262. charset ? "link.charset = 'utf-8';" : "",
  263. `if (${RuntimeGlobals.scriptNonce}) {`,
  264. Template.indent(
  265. `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
  266. ),
  267. "}",
  268. scriptType === "module"
  269. ? 'link.rel = "modulepreload";'
  270. : 'link.rel = "preload";',
  271. scriptType === "module" ? "" : 'link.as = "script";',
  272. `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`,
  273. crossOriginLoading
  274. ? crossOriginLoading === "use-credentials"
  275. ? 'link.crossOrigin = "use-credentials";'
  276. : Template.asString([
  277. "if (link.href.indexOf(window.location.origin + '/') !== 0) {",
  278. Template.indent(
  279. `link.crossOrigin = ${JSON.stringify(
  280. crossOriginLoading
  281. )};`
  282. ),
  283. "}"
  284. ])
  285. : ""
  286. ]),
  287. chunk
  288. ),
  289. "document.head.appendChild(link);"
  290. ]),
  291. "}"
  292. ])};`
  293. : "// no preloaded",
  294. "",
  295. withHmr
  296. ? Template.asString([
  297. "var currentUpdatedModulesList;",
  298. "var waitingUpdateResolves = {};",
  299. "function loadUpdateChunk(chunkId, updatedModulesList) {",
  300. Template.indent([
  301. "currentUpdatedModulesList = updatedModulesList;",
  302. `return new Promise(${runtimeTemplate.basicFunction(
  303. "resolve, reject",
  304. [
  305. "waitingUpdateResolves[chunkId] = resolve;",
  306. "// start update chunk loading",
  307. `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId);`,
  308. "// create error before stack unwound to get useful stacktrace later",
  309. "var error = new Error();",
  310. `var loadingEnded = ${runtimeTemplate.basicFunction("event", [
  311. "if(waitingUpdateResolves[chunkId]) {",
  312. Template.indent([
  313. "waitingUpdateResolves[chunkId] = undefined",
  314. "var errorType = event && (event.type === 'load' ? 'missing' : event.type);",
  315. "var realSrc = event && event.target && event.target.src;",
  316. "error.message = 'Loading hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';",
  317. "error.name = 'ChunkLoadError';",
  318. "error.type = errorType;",
  319. "error.request = realSrc;",
  320. "reject(error);"
  321. ]),
  322. "}"
  323. ])};`,
  324. `${RuntimeGlobals.loadScript}(url, loadingEnded);`
  325. ]
  326. )});`
  327. ]),
  328. "}",
  329. "",
  330. `${globalObject}[${JSON.stringify(
  331. hotUpdateGlobal
  332. )}] = ${runtimeTemplate.basicFunction(
  333. "chunkId, moreModules, runtime",
  334. [
  335. "for(var moduleId in moreModules) {",
  336. Template.indent([
  337. `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
  338. Template.indent([
  339. "currentUpdate[moduleId] = moreModules[moduleId];",
  340. "if(currentUpdatedModulesList) currentUpdatedModulesList.push(moduleId);"
  341. ]),
  342. "}"
  343. ]),
  344. "}",
  345. "if(runtime) currentUpdateRuntime.push(runtime);",
  346. "if(waitingUpdateResolves[chunkId]) {",
  347. Template.indent([
  348. "waitingUpdateResolves[chunkId]();",
  349. "waitingUpdateResolves[chunkId] = undefined;"
  350. ]),
  351. "}"
  352. ]
  353. )};`,
  354. "",
  355. Template.getFunctionContent(
  356. require("../hmr/JavascriptHotModuleReplacement.runtime.js")
  357. )
  358. .replace(/\$key\$/g, "jsonp")
  359. .replace(/\$installedChunks\$/g, "installedChunks")
  360. .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk")
  361. .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache)
  362. .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories)
  363. .replace(
  364. /\$ensureChunkHandlers\$/g,
  365. RuntimeGlobals.ensureChunkHandlers
  366. )
  367. .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty)
  368. .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData)
  369. .replace(
  370. /\$hmrDownloadUpdateHandlers\$/g,
  371. RuntimeGlobals.hmrDownloadUpdateHandlers
  372. )
  373. .replace(
  374. /\$hmrInvalidateModuleHandlers\$/g,
  375. RuntimeGlobals.hmrInvalidateModuleHandlers
  376. )
  377. ])
  378. : "// no HMR",
  379. "",
  380. withHmrManifest
  381. ? Template.asString([
  382. `${
  383. RuntimeGlobals.hmrDownloadManifest
  384. } = ${runtimeTemplate.basicFunction("", [
  385. 'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");',
  386. `return fetch(${RuntimeGlobals.publicPath} + ${
  387. RuntimeGlobals.getUpdateManifestFilename
  388. }()).then(${runtimeTemplate.basicFunction("response", [
  389. "if(response.status === 404) return; // no update available",
  390. 'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);',
  391. "return response.json();"
  392. ])});`
  393. ])};`
  394. ])
  395. : "// no HMR manifest",
  396. "",
  397. withOnChunkLoad
  398. ? `${
  399. RuntimeGlobals.onChunksLoaded
  400. }.j = ${runtimeTemplate.returningFunction(
  401. "installedChunks[chunkId] === 0",
  402. "chunkId"
  403. )};`
  404. : "// no on chunks loaded",
  405. "",
  406. withCallback || withLoading
  407. ? Template.asString([
  408. "// install a JSONP callback for chunk loading",
  409. `var webpackJsonpCallback = ${runtimeTemplate.basicFunction(
  410. "parentChunkLoadingFunction, data",
  411. [
  412. runtimeTemplate.destructureArray(
  413. ["chunkIds", "moreModules", "runtime"],
  414. "data"
  415. ),
  416. '// add "moreModules" to the modules object,',
  417. '// then flag all "chunkIds" as loaded and fire callback',
  418. "var moduleId, chunkId, i = 0;",
  419. `if(chunkIds.some(${runtimeTemplate.returningFunction(
  420. "installedChunks[id] !== 0",
  421. "id"
  422. )})) {`,
  423. Template.indent([
  424. "for(moduleId in moreModules) {",
  425. Template.indent([
  426. `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
  427. Template.indent(
  428. `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];`
  429. ),
  430. "}"
  431. ]),
  432. "}",
  433. `if(runtime) var result = runtime(${RuntimeGlobals.require});`
  434. ]),
  435. "}",
  436. "if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);",
  437. "for(;i < chunkIds.length; i++) {",
  438. Template.indent([
  439. "chunkId = chunkIds[i];",
  440. `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`,
  441. Template.indent("installedChunks[chunkId][0]();"),
  442. "}",
  443. "installedChunks[chunkId] = 0;"
  444. ]),
  445. "}",
  446. withOnChunkLoad
  447. ? `return ${RuntimeGlobals.onChunksLoaded}(result);`
  448. : ""
  449. ]
  450. )}`,
  451. "",
  452. `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`,
  453. "chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));",
  454. "chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));"
  455. ])
  456. : "// no jsonp function"
  457. ]);
  458. }
  459. }
  460. module.exports = JsonpChunkLoadingRuntimeModule;