ModuleChunkLoadingRuntimeModule.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 {
  11. getChunkFilenameTemplate,
  12. chunkHasJs
  13. } = require("../javascript/JavascriptModulesPlugin");
  14. const { getInitialChunkIds } = require("../javascript/StartupHelpers");
  15. const compileBooleanMatcher = require("../util/compileBooleanMatcher");
  16. const { getUndoPath } = require("../util/identifier");
  17. /** @typedef {import("../Chunk")} Chunk */
  18. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  19. /** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
  20. /**
  21. * @typedef {object} JsonpCompilationPluginHooks
  22. * @property {SyncWaterfallHook<[string, Chunk]>} linkPreload
  23. * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch
  24. */
  25. /** @type {WeakMap<Compilation, JsonpCompilationPluginHooks>} */
  26. const compilationHooksMap = new WeakMap();
  27. class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
  28. /**
  29. * @param {Compilation} compilation the compilation
  30. * @returns {JsonpCompilationPluginHooks} hooks
  31. */
  32. static getCompilationHooks(compilation) {
  33. if (!(compilation instanceof Compilation)) {
  34. throw new TypeError(
  35. "The 'compilation' argument must be an instance of Compilation"
  36. );
  37. }
  38. let hooks = compilationHooksMap.get(compilation);
  39. if (hooks === undefined) {
  40. hooks = {
  41. linkPreload: new SyncWaterfallHook(["source", "chunk"]),
  42. linkPrefetch: new SyncWaterfallHook(["source", "chunk"])
  43. };
  44. compilationHooksMap.set(compilation, hooks);
  45. }
  46. return hooks;
  47. }
  48. /**
  49. * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements
  50. */
  51. constructor(runtimeRequirements) {
  52. super("import chunk loading", RuntimeModule.STAGE_ATTACH);
  53. this._runtimeRequirements = runtimeRequirements;
  54. }
  55. /**
  56. * @private
  57. * @param {Chunk} chunk chunk
  58. * @param {string} rootOutputDir root output directory
  59. * @returns {string} generated code
  60. */
  61. _generateBaseUri(chunk, rootOutputDir) {
  62. const options = chunk.getEntryOptions();
  63. if (options && options.baseUri) {
  64. return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`;
  65. }
  66. const compilation = /** @type {Compilation} */ (this.compilation);
  67. const {
  68. outputOptions: { importMetaName }
  69. } = compilation;
  70. return `${RuntimeGlobals.baseURI} = new URL(${JSON.stringify(
  71. rootOutputDir
  72. )}, ${importMetaName}.url);`;
  73. }
  74. /**
  75. * @returns {string | null} runtime code
  76. */
  77. generate() {
  78. const compilation = /** @type {Compilation} */ (this.compilation);
  79. const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
  80. const chunk = /** @type {Chunk} */ (this.chunk);
  81. const {
  82. runtimeTemplate,
  83. outputOptions: { environment, importFunctionName, crossOriginLoading }
  84. } = compilation;
  85. const fn = RuntimeGlobals.ensureChunkHandlers;
  86. const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI);
  87. const withExternalInstallChunk = this._runtimeRequirements.has(
  88. RuntimeGlobals.externalInstallChunk
  89. );
  90. const withLoading = this._runtimeRequirements.has(
  91. RuntimeGlobals.ensureChunkHandlers
  92. );
  93. const withOnChunkLoad = this._runtimeRequirements.has(
  94. RuntimeGlobals.onChunksLoaded
  95. );
  96. const withHmr = this._runtimeRequirements.has(
  97. RuntimeGlobals.hmrDownloadUpdateHandlers
  98. );
  99. const { linkPreload, linkPrefetch } =
  100. ModuleChunkLoadingRuntimeModule.getCompilationHooks(compilation);
  101. const withPrefetch =
  102. environment.document &&
  103. this._runtimeRequirements.has(RuntimeGlobals.prefetchChunkHandlers);
  104. const withPreload =
  105. environment.document &&
  106. this._runtimeRequirements.has(RuntimeGlobals.preloadChunkHandlers);
  107. const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs);
  108. const hasJsMatcher = compileBooleanMatcher(conditionMap);
  109. const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs);
  110. const outputName = compilation.getPath(
  111. getChunkFilenameTemplate(chunk, compilation.outputOptions),
  112. {
  113. chunk,
  114. contentHashType: "javascript"
  115. }
  116. );
  117. const rootOutputDir = getUndoPath(
  118. outputName,
  119. /** @type {string} */ (compilation.outputOptions.path),
  120. true
  121. );
  122. const stateExpression = withHmr
  123. ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_module`
  124. : undefined;
  125. return Template.asString([
  126. withBaseURI
  127. ? this._generateBaseUri(chunk, rootOutputDir)
  128. : "// no baseURI",
  129. "",
  130. "// object to store loaded and loading chunks",
  131. "// undefined = chunk not loaded, null = chunk preloaded/prefetched",
  132. "// [resolve, Promise] = chunk loading, 0 = chunk loaded",
  133. `var installedChunks = ${
  134. stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
  135. }{`,
  136. Template.indent(
  137. Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join(
  138. ",\n"
  139. )
  140. ),
  141. "};",
  142. "",
  143. withLoading || withExternalInstallChunk
  144. ? `var installChunk = ${runtimeTemplate.basicFunction("data", [
  145. runtimeTemplate.destructureObject(
  146. ["ids", "modules", "runtime"],
  147. "data"
  148. ),
  149. '// add "modules" to the modules object,',
  150. '// then flag all "ids" as loaded and fire callback',
  151. "var moduleId, chunkId, i = 0;",
  152. "for(moduleId in modules) {",
  153. Template.indent([
  154. `if(${RuntimeGlobals.hasOwnProperty}(modules, moduleId)) {`,
  155. Template.indent(
  156. `${RuntimeGlobals.moduleFactories}[moduleId] = modules[moduleId];`
  157. ),
  158. "}"
  159. ]),
  160. "}",
  161. `if(runtime) runtime(${RuntimeGlobals.require});`,
  162. "for(;i < ids.length; i++) {",
  163. Template.indent([
  164. "chunkId = ids[i];",
  165. `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`,
  166. Template.indent("installedChunks[chunkId][0]();"),
  167. "}",
  168. "installedChunks[ids[i]] = 0;"
  169. ]),
  170. "}",
  171. withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : ""
  172. ])}`
  173. : "// no install chunk",
  174. "",
  175. withLoading
  176. ? Template.asString([
  177. `${fn}.j = ${runtimeTemplate.basicFunction(
  178. "chunkId, promises",
  179. hasJsMatcher !== false
  180. ? Template.indent([
  181. "// import() chunk loading for javascript",
  182. `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`,
  183. 'if(installedChunkData !== 0) { // 0 means "already installed".',
  184. Template.indent([
  185. "",
  186. '// a Promise means "currently loading".',
  187. "if(installedChunkData) {",
  188. Template.indent([
  189. "promises.push(installedChunkData[1]);"
  190. ]),
  191. "} else {",
  192. Template.indent([
  193. hasJsMatcher === true
  194. ? "if(true) { // all chunks have JS"
  195. : `if(${hasJsMatcher("chunkId")}) {`,
  196. Template.indent([
  197. "// setup Promise in chunk cache",
  198. `var promise = ${importFunctionName}(${JSON.stringify(
  199. rootOutputDir
  200. )} + ${
  201. RuntimeGlobals.getChunkScriptFilename
  202. }(chunkId)).then(installChunk, ${runtimeTemplate.basicFunction(
  203. "e",
  204. [
  205. "if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;",
  206. "throw e;"
  207. ]
  208. )});`,
  209. `var promise = Promise.race([promise, new Promise(${runtimeTemplate.expressionFunction(
  210. `installedChunkData = installedChunks[chunkId] = [resolve]`,
  211. "resolve"
  212. )})])`,
  213. `promises.push(installedChunkData[1] = promise);`
  214. ]),
  215. hasJsMatcher === true
  216. ? "}"
  217. : "} else installedChunks[chunkId] = 0;"
  218. ]),
  219. "}"
  220. ]),
  221. "}"
  222. ])
  223. : Template.indent(["installedChunks[chunkId] = 0;"])
  224. )};`
  225. ])
  226. : "// no chunk on demand loading",
  227. "",
  228. withPrefetch && hasJsMatcher !== false
  229. ? `${
  230. RuntimeGlobals.prefetchChunkHandlers
  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. linkPrefetch.call(
  240. Template.asString([
  241. "var link = document.createElement('link');",
  242. crossOriginLoading
  243. ? `link.crossOrigin = ${JSON.stringify(
  244. crossOriginLoading
  245. )};`
  246. : "",
  247. `if (${RuntimeGlobals.scriptNonce}) {`,
  248. Template.indent(
  249. `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
  250. ),
  251. "}",
  252. 'link.rel = "prefetch";',
  253. 'link.as = "script";',
  254. `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`
  255. ]),
  256. chunk
  257. ),
  258. "document.head.appendChild(link);"
  259. ]),
  260. "}"
  261. ])};`
  262. : "// no prefetching",
  263. "",
  264. withPreload && hasJsMatcher !== false
  265. ? `${
  266. RuntimeGlobals.preloadChunkHandlers
  267. }.j = ${runtimeTemplate.basicFunction("chunkId", [
  268. `if((!${
  269. RuntimeGlobals.hasOwnProperty
  270. }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${
  271. hasJsMatcher === true ? "true" : hasJsMatcher("chunkId")
  272. }) {`,
  273. Template.indent([
  274. "installedChunks[chunkId] = null;",
  275. linkPreload.call(
  276. Template.asString([
  277. "var link = document.createElement('link');",
  278. "link.charset = 'utf-8';",
  279. `if (${RuntimeGlobals.scriptNonce}) {`,
  280. Template.indent(
  281. `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
  282. ),
  283. "}",
  284. 'link.rel = "modulepreload";',
  285. `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`,
  286. crossOriginLoading
  287. ? crossOriginLoading === "use-credentials"
  288. ? 'link.crossOrigin = "use-credentials";'
  289. : Template.asString([
  290. "if (link.href.indexOf(window.location.origin + '/') !== 0) {",
  291. Template.indent(
  292. `link.crossOrigin = ${JSON.stringify(
  293. crossOriginLoading
  294. )};`
  295. ),
  296. "}"
  297. ])
  298. : ""
  299. ]),
  300. chunk
  301. ),
  302. "document.head.appendChild(link);"
  303. ]),
  304. "}"
  305. ])};`
  306. : "// no preloaded",
  307. "",
  308. withExternalInstallChunk
  309. ? Template.asString([
  310. `${RuntimeGlobals.externalInstallChunk} = installChunk;`
  311. ])
  312. : "// no external install chunk",
  313. "",
  314. withOnChunkLoad
  315. ? `${
  316. RuntimeGlobals.onChunksLoaded
  317. }.j = ${runtimeTemplate.returningFunction(
  318. "installedChunks[chunkId] === 0",
  319. "chunkId"
  320. )};`
  321. : "// no on chunks loaded"
  322. ]);
  323. }
  324. }
  325. module.exports = ModuleChunkLoadingRuntimeModule;