ModuleChunkLoadingRuntimeModule.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. /**
  19. * @typedef {Object} JsonpCompilationPluginHooks
  20. * @property {SyncWaterfallHook<[string, Chunk]>} linkPreload
  21. * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch
  22. */
  23. /** @type {WeakMap<Compilation, JsonpCompilationPluginHooks>} */
  24. const compilationHooksMap = new WeakMap();
  25. class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
  26. /**
  27. * @param {Compilation} compilation the compilation
  28. * @returns {JsonpCompilationPluginHooks} hooks
  29. */
  30. static getCompilationHooks(compilation) {
  31. if (!(compilation instanceof Compilation)) {
  32. throw new TypeError(
  33. "The 'compilation' argument must be an instance of Compilation"
  34. );
  35. }
  36. let hooks = compilationHooksMap.get(compilation);
  37. if (hooks === undefined) {
  38. hooks = {
  39. linkPreload: new SyncWaterfallHook(["source", "chunk"]),
  40. linkPrefetch: new SyncWaterfallHook(["source", "chunk"])
  41. };
  42. compilationHooksMap.set(compilation, hooks);
  43. }
  44. return hooks;
  45. }
  46. constructor(runtimeRequirements) {
  47. super("import chunk loading", RuntimeModule.STAGE_ATTACH);
  48. this._runtimeRequirements = runtimeRequirements;
  49. }
  50. /**
  51. * @returns {string} runtime code
  52. */
  53. generate() {
  54. const { compilation, chunk } = this;
  55. const {
  56. runtimeTemplate,
  57. chunkGraph,
  58. outputOptions: { importFunctionName, importMetaName }
  59. } = compilation;
  60. const fn = RuntimeGlobals.ensureChunkHandlers;
  61. const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI);
  62. const withExternalInstallChunk = this._runtimeRequirements.has(
  63. RuntimeGlobals.externalInstallChunk
  64. );
  65. const withLoading = this._runtimeRequirements.has(
  66. RuntimeGlobals.ensureChunkHandlers
  67. );
  68. const withOnChunkLoad = this._runtimeRequirements.has(
  69. RuntimeGlobals.onChunksLoaded
  70. );
  71. const withHmr = this._runtimeRequirements.has(
  72. RuntimeGlobals.hmrDownloadUpdateHandlers
  73. );
  74. const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs);
  75. const hasJsMatcher = compileBooleanMatcher(conditionMap);
  76. const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs);
  77. const outputName = this.compilation.getPath(
  78. getChunkFilenameTemplate(chunk, this.compilation.outputOptions),
  79. {
  80. chunk,
  81. contentHashType: "javascript"
  82. }
  83. );
  84. const rootOutputDir = getUndoPath(
  85. outputName,
  86. this.compilation.outputOptions.path,
  87. true
  88. );
  89. const stateExpression = withHmr
  90. ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_module`
  91. : undefined;
  92. return Template.asString([
  93. withBaseURI
  94. ? Template.asString([
  95. `${RuntimeGlobals.baseURI} = new URL(${JSON.stringify(
  96. rootOutputDir
  97. )}, ${importMetaName}.url);`
  98. ])
  99. : "// no baseURI",
  100. "",
  101. "// object to store loaded and loading chunks",
  102. "// undefined = chunk not loaded, null = chunk preloaded/prefetched",
  103. "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded",
  104. `var installedChunks = ${
  105. stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
  106. }{`,
  107. Template.indent(
  108. Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join(
  109. ",\n"
  110. )
  111. ),
  112. "};",
  113. "",
  114. withLoading || withExternalInstallChunk
  115. ? `var installChunk = ${runtimeTemplate.basicFunction("data", [
  116. runtimeTemplate.destructureObject(
  117. ["ids", "modules", "runtime"],
  118. "data"
  119. ),
  120. '// add "modules" to the modules object,',
  121. '// then flag all "ids" as loaded and fire callback',
  122. "var moduleId, chunkId, i = 0;",
  123. "for(moduleId in modules) {",
  124. Template.indent([
  125. `if(${RuntimeGlobals.hasOwnProperty}(modules, moduleId)) {`,
  126. Template.indent(
  127. `${RuntimeGlobals.moduleFactories}[moduleId] = modules[moduleId];`
  128. ),
  129. "}"
  130. ]),
  131. "}",
  132. "if(runtime) runtime(__webpack_require__);",
  133. "for(;i < ids.length; i++) {",
  134. Template.indent([
  135. "chunkId = ids[i];",
  136. `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`,
  137. Template.indent("installedChunks[chunkId][0]();"),
  138. "}",
  139. "installedChunks[ids[i]] = 0;"
  140. ]),
  141. "}",
  142. withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : ""
  143. ])}`
  144. : "// no install chunk",
  145. "",
  146. withLoading
  147. ? Template.asString([
  148. `${fn}.j = ${runtimeTemplate.basicFunction(
  149. "chunkId, promises",
  150. hasJsMatcher !== false
  151. ? Template.indent([
  152. "// import() chunk loading for javascript",
  153. `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`,
  154. 'if(installedChunkData !== 0) { // 0 means "already installed".',
  155. Template.indent([
  156. "",
  157. '// a Promise means "currently loading".',
  158. "if(installedChunkData) {",
  159. Template.indent([
  160. "promises.push(installedChunkData[1]);"
  161. ]),
  162. "} else {",
  163. Template.indent([
  164. hasJsMatcher === true
  165. ? "if(true) { // all chunks have JS"
  166. : `if(${hasJsMatcher("chunkId")}) {`,
  167. Template.indent([
  168. "// setup Promise in chunk cache",
  169. `var promise = ${importFunctionName}(${JSON.stringify(
  170. rootOutputDir
  171. )} + ${
  172. RuntimeGlobals.getChunkScriptFilename
  173. }(chunkId)).then(installChunk, ${runtimeTemplate.basicFunction(
  174. "e",
  175. [
  176. "if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;",
  177. "throw e;"
  178. ]
  179. )});`,
  180. `var promise = Promise.race([promise, new Promise(${runtimeTemplate.expressionFunction(
  181. `installedChunkData = installedChunks[chunkId] = [resolve]`,
  182. "resolve"
  183. )})])`,
  184. `promises.push(installedChunkData[1] = promise);`
  185. ]),
  186. "} else installedChunks[chunkId] = 0;"
  187. ]),
  188. "}"
  189. ]),
  190. "}"
  191. ])
  192. : Template.indent(["installedChunks[chunkId] = 0;"])
  193. )};`
  194. ])
  195. : "// no chunk on demand loading",
  196. "",
  197. withExternalInstallChunk
  198. ? Template.asString([
  199. `${RuntimeGlobals.externalInstallChunk} = installChunk;`
  200. ])
  201. : "// no external install chunk",
  202. "",
  203. withOnChunkLoad
  204. ? `${
  205. RuntimeGlobals.onChunksLoaded
  206. }.j = ${runtimeTemplate.returningFunction(
  207. "installedChunks[chunkId] === 0",
  208. "chunkId"
  209. )};`
  210. : "// no on chunks loaded"
  211. ]);
  212. }
  213. }
  214. module.exports = ModuleChunkLoadingRuntimeModule;