JsonpChunkLoadingRuntimeModule.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. ? crossOriginLoading === "use-credentials"
  256. ? 'link.crossOrigin = "use-credentials";'
  257. : Template.asString([
  258. "if (link.href.indexOf(window.location.origin + '/') !== 0) {",
  259. Template.indent(
  260. `link.crossOrigin = ${JSON.stringify(
  261. crossOriginLoading
  262. )};`
  263. ),
  264. "}"
  265. ])
  266. : ""
  267. ]),
  268. chunk
  269. ),
  270. "document.head.appendChild(link);"
  271. ]),
  272. "}"
  273. ])};`
  274. : "// no preloaded",
  275. "",
  276. withHmr
  277. ? Template.asString([
  278. "var currentUpdatedModulesList;",
  279. "var waitingUpdateResolves = {};",
  280. "function loadUpdateChunk(chunkId, updatedModulesList) {",
  281. Template.indent([
  282. "currentUpdatedModulesList = updatedModulesList;",
  283. `return new Promise(${runtimeTemplate.basicFunction(
  284. "resolve, reject",
  285. [
  286. "waitingUpdateResolves[chunkId] = resolve;",
  287. "// start update chunk loading",
  288. `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId);`,
  289. "// create error before stack unwound to get useful stacktrace later",
  290. "var error = new Error();",
  291. `var loadingEnded = ${runtimeTemplate.basicFunction("event", [
  292. "if(waitingUpdateResolves[chunkId]) {",
  293. Template.indent([
  294. "waitingUpdateResolves[chunkId] = undefined",
  295. "var errorType = event && (event.type === 'load' ? 'missing' : event.type);",
  296. "var realSrc = event && event.target && event.target.src;",
  297. "error.message = 'Loading hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';",
  298. "error.name = 'ChunkLoadError';",
  299. "error.type = errorType;",
  300. "error.request = realSrc;",
  301. "reject(error);"
  302. ]),
  303. "}"
  304. ])};`,
  305. `${RuntimeGlobals.loadScript}(url, loadingEnded);`
  306. ]
  307. )});`
  308. ]),
  309. "}",
  310. "",
  311. `${globalObject}[${JSON.stringify(
  312. hotUpdateGlobal
  313. )}] = ${runtimeTemplate.basicFunction(
  314. "chunkId, moreModules, runtime",
  315. [
  316. "for(var moduleId in moreModules) {",
  317. Template.indent([
  318. `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
  319. Template.indent([
  320. "currentUpdate[moduleId] = moreModules[moduleId];",
  321. "if(currentUpdatedModulesList) currentUpdatedModulesList.push(moduleId);"
  322. ]),
  323. "}"
  324. ]),
  325. "}",
  326. "if(runtime) currentUpdateRuntime.push(runtime);",
  327. "if(waitingUpdateResolves[chunkId]) {",
  328. Template.indent([
  329. "waitingUpdateResolves[chunkId]();",
  330. "waitingUpdateResolves[chunkId] = undefined;"
  331. ]),
  332. "}"
  333. ]
  334. )};`,
  335. "",
  336. Template.getFunctionContent(
  337. require("../hmr/JavascriptHotModuleReplacement.runtime.js")
  338. )
  339. .replace(/\$key\$/g, "jsonp")
  340. .replace(/\$installedChunks\$/g, "installedChunks")
  341. .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk")
  342. .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache)
  343. .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories)
  344. .replace(
  345. /\$ensureChunkHandlers\$/g,
  346. RuntimeGlobals.ensureChunkHandlers
  347. )
  348. .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty)
  349. .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData)
  350. .replace(
  351. /\$hmrDownloadUpdateHandlers\$/g,
  352. RuntimeGlobals.hmrDownloadUpdateHandlers
  353. )
  354. .replace(
  355. /\$hmrInvalidateModuleHandlers\$/g,
  356. RuntimeGlobals.hmrInvalidateModuleHandlers
  357. )
  358. ])
  359. : "// no HMR",
  360. "",
  361. withHmrManifest
  362. ? Template.asString([
  363. `${
  364. RuntimeGlobals.hmrDownloadManifest
  365. } = ${runtimeTemplate.basicFunction("", [
  366. 'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");',
  367. `return fetch(${RuntimeGlobals.publicPath} + ${
  368. RuntimeGlobals.getUpdateManifestFilename
  369. }()).then(${runtimeTemplate.basicFunction("response", [
  370. "if(response.status === 404) return; // no update available",
  371. 'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);',
  372. "return response.json();"
  373. ])});`
  374. ])};`
  375. ])
  376. : "// no HMR manifest",
  377. "",
  378. withOnChunkLoad
  379. ? `${
  380. RuntimeGlobals.onChunksLoaded
  381. }.j = ${runtimeTemplate.returningFunction(
  382. "installedChunks[chunkId] === 0",
  383. "chunkId"
  384. )};`
  385. : "// no on chunks loaded",
  386. "",
  387. withCallback || withLoading
  388. ? Template.asString([
  389. "// install a JSONP callback for chunk loading",
  390. `var webpackJsonpCallback = ${runtimeTemplate.basicFunction(
  391. "parentChunkLoadingFunction, data",
  392. [
  393. runtimeTemplate.destructureArray(
  394. ["chunkIds", "moreModules", "runtime"],
  395. "data"
  396. ),
  397. '// add "moreModules" to the modules object,',
  398. '// then flag all "chunkIds" as loaded and fire callback',
  399. "var moduleId, chunkId, i = 0;",
  400. `if(chunkIds.some(${runtimeTemplate.returningFunction(
  401. "installedChunks[id] !== 0",
  402. "id"
  403. )})) {`,
  404. Template.indent([
  405. "for(moduleId in moreModules) {",
  406. Template.indent([
  407. `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
  408. Template.indent(
  409. `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];`
  410. ),
  411. "}"
  412. ]),
  413. "}",
  414. "if(runtime) var result = runtime(__webpack_require__);"
  415. ]),
  416. "}",
  417. "if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);",
  418. "for(;i < chunkIds.length; i++) {",
  419. Template.indent([
  420. "chunkId = chunkIds[i];",
  421. `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`,
  422. Template.indent("installedChunks[chunkId][0]();"),
  423. "}",
  424. "installedChunks[chunkId] = 0;"
  425. ]),
  426. "}",
  427. withOnChunkLoad
  428. ? `return ${RuntimeGlobals.onChunksLoaded}(result);`
  429. : ""
  430. ]
  431. )}`,
  432. "",
  433. `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`,
  434. "chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));",
  435. "chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));"
  436. ])
  437. : "// no jsonp function"
  438. ]);
  439. }
  440. }
  441. module.exports = JsonpChunkLoadingRuntimeModule;