ModuleChunkLoadingRuntimeModule.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. * @private
  52. * @param {Chunk} chunk chunk
  53. * @param {string} rootOutputDir root output directory
  54. * @returns {string} generated code
  55. */
  56. _generateBaseUri(chunk, rootOutputDir) {
  57. const options = chunk.getEntryOptions();
  58. if (options && options.baseUri) {
  59. return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`;
  60. }
  61. const {
  62. compilation: {
  63. outputOptions: { importMetaName }
  64. }
  65. } = this;
  66. return `${RuntimeGlobals.baseURI} = new URL(${JSON.stringify(
  67. rootOutputDir
  68. )}, ${importMetaName}.url);`;
  69. }
  70. /**
  71. * @returns {string} runtime code
  72. */
  73. generate() {
  74. const { compilation, chunk, chunkGraph } = this;
  75. const {
  76. runtimeTemplate,
  77. outputOptions: { importFunctionName }
  78. } = compilation;
  79. const fn = RuntimeGlobals.ensureChunkHandlers;
  80. const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI);
  81. const withExternalInstallChunk = this._runtimeRequirements.has(
  82. RuntimeGlobals.externalInstallChunk
  83. );
  84. const withLoading = this._runtimeRequirements.has(
  85. RuntimeGlobals.ensureChunkHandlers
  86. );
  87. const withOnChunkLoad = this._runtimeRequirements.has(
  88. RuntimeGlobals.onChunksLoaded
  89. );
  90. const withHmr = this._runtimeRequirements.has(
  91. RuntimeGlobals.hmrDownloadUpdateHandlers
  92. );
  93. const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs);
  94. const hasJsMatcher = compileBooleanMatcher(conditionMap);
  95. const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs);
  96. const outputName = this.compilation.getPath(
  97. getChunkFilenameTemplate(chunk, this.compilation.outputOptions),
  98. {
  99. chunk,
  100. contentHashType: "javascript"
  101. }
  102. );
  103. const rootOutputDir = getUndoPath(
  104. outputName,
  105. this.compilation.outputOptions.path,
  106. true
  107. );
  108. const stateExpression = withHmr
  109. ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_module`
  110. : undefined;
  111. return Template.asString([
  112. withBaseURI
  113. ? this._generateBaseUri(chunk, rootOutputDir)
  114. : "// no baseURI",
  115. "",
  116. "// object to store loaded and loading chunks",
  117. "// undefined = chunk not loaded, null = chunk preloaded/prefetched",
  118. "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded",
  119. `var installedChunks = ${
  120. stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
  121. }{`,
  122. Template.indent(
  123. Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join(
  124. ",\n"
  125. )
  126. ),
  127. "};",
  128. "",
  129. withLoading || withExternalInstallChunk
  130. ? `var installChunk = ${runtimeTemplate.basicFunction("data", [
  131. runtimeTemplate.destructureObject(
  132. ["ids", "modules", "runtime"],
  133. "data"
  134. ),
  135. '// add "modules" to the modules object,',
  136. '// then flag all "ids" as loaded and fire callback',
  137. "var moduleId, chunkId, i = 0;",
  138. "for(moduleId in modules) {",
  139. Template.indent([
  140. `if(${RuntimeGlobals.hasOwnProperty}(modules, moduleId)) {`,
  141. Template.indent(
  142. `${RuntimeGlobals.moduleFactories}[moduleId] = modules[moduleId];`
  143. ),
  144. "}"
  145. ]),
  146. "}",
  147. "if(runtime) runtime(__webpack_require__);",
  148. "for(;i < ids.length; i++) {",
  149. Template.indent([
  150. "chunkId = ids[i];",
  151. `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`,
  152. Template.indent("installedChunks[chunkId][0]();"),
  153. "}",
  154. "installedChunks[ids[i]] = 0;"
  155. ]),
  156. "}",
  157. withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : ""
  158. ])}`
  159. : "// no install chunk",
  160. "",
  161. withLoading
  162. ? Template.asString([
  163. `${fn}.j = ${runtimeTemplate.basicFunction(
  164. "chunkId, promises",
  165. hasJsMatcher !== false
  166. ? Template.indent([
  167. "// import() chunk loading for javascript",
  168. `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`,
  169. 'if(installedChunkData !== 0) { // 0 means "already installed".',
  170. Template.indent([
  171. "",
  172. '// a Promise means "currently loading".',
  173. "if(installedChunkData) {",
  174. Template.indent([
  175. "promises.push(installedChunkData[1]);"
  176. ]),
  177. "} else {",
  178. Template.indent([
  179. hasJsMatcher === true
  180. ? "if(true) { // all chunks have JS"
  181. : `if(${hasJsMatcher("chunkId")}) {`,
  182. Template.indent([
  183. "// setup Promise in chunk cache",
  184. `var promise = ${importFunctionName}(${JSON.stringify(
  185. rootOutputDir
  186. )} + ${
  187. RuntimeGlobals.getChunkScriptFilename
  188. }(chunkId)).then(installChunk, ${runtimeTemplate.basicFunction(
  189. "e",
  190. [
  191. "if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;",
  192. "throw e;"
  193. ]
  194. )});`,
  195. `var promise = Promise.race([promise, new Promise(${runtimeTemplate.expressionFunction(
  196. `installedChunkData = installedChunks[chunkId] = [resolve]`,
  197. "resolve"
  198. )})])`,
  199. `promises.push(installedChunkData[1] = promise);`
  200. ]),
  201. "} else installedChunks[chunkId] = 0;"
  202. ]),
  203. "}"
  204. ]),
  205. "}"
  206. ])
  207. : Template.indent(["installedChunks[chunkId] = 0;"])
  208. )};`
  209. ])
  210. : "// no chunk on demand loading",
  211. "",
  212. withExternalInstallChunk
  213. ? Template.asString([
  214. `${RuntimeGlobals.externalInstallChunk} = installChunk;`
  215. ])
  216. : "// no external install chunk",
  217. "",
  218. withOnChunkLoad
  219. ? `${
  220. RuntimeGlobals.onChunksLoaded
  221. }.j = ${runtimeTemplate.returningFunction(
  222. "installedChunks[chunkId] === 0",
  223. "chunkId"
  224. )};`
  225. : "// no on chunks loaded"
  226. ]);
  227. }
  228. }
  229. module.exports = ModuleChunkLoadingRuntimeModule;