JsonpChunkLoadingRuntimeModule.js 16 KB

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