JsonpChunkLoadingRuntimeModule.js 15 KB

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