ModuleChunkLoadingRuntimeModule.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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: { importFunctionName }
  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 conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs);
  100. const hasJsMatcher = compileBooleanMatcher(conditionMap);
  101. const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs);
  102. const outputName = compilation.getPath(
  103. getChunkFilenameTemplate(chunk, compilation.outputOptions),
  104. {
  105. chunk,
  106. contentHashType: "javascript"
  107. }
  108. );
  109. const rootOutputDir = getUndoPath(
  110. outputName,
  111. /** @type {string} */ (compilation.outputOptions.path),
  112. true
  113. );
  114. const stateExpression = withHmr
  115. ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_module`
  116. : undefined;
  117. return Template.asString([
  118. withBaseURI
  119. ? this._generateBaseUri(chunk, rootOutputDir)
  120. : "// no baseURI",
  121. "",
  122. "// object to store loaded and loading chunks",
  123. "// undefined = chunk not loaded, null = chunk preloaded/prefetched",
  124. "// [resolve, Promise] = chunk loading, 0 = chunk loaded",
  125. `var installedChunks = ${
  126. stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
  127. }{`,
  128. Template.indent(
  129. Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join(
  130. ",\n"
  131. )
  132. ),
  133. "};",
  134. "",
  135. withLoading || withExternalInstallChunk
  136. ? `var installChunk = ${runtimeTemplate.basicFunction("data", [
  137. runtimeTemplate.destructureObject(
  138. ["ids", "modules", "runtime"],
  139. "data"
  140. ),
  141. '// add "modules" to the modules object,',
  142. '// then flag all "ids" as loaded and fire callback',
  143. "var moduleId, chunkId, i = 0;",
  144. "for(moduleId in modules) {",
  145. Template.indent([
  146. `if(${RuntimeGlobals.hasOwnProperty}(modules, moduleId)) {`,
  147. Template.indent(
  148. `${RuntimeGlobals.moduleFactories}[moduleId] = modules[moduleId];`
  149. ),
  150. "}"
  151. ]),
  152. "}",
  153. `if(runtime) runtime(${RuntimeGlobals.require});`,
  154. "for(;i < ids.length; i++) {",
  155. Template.indent([
  156. "chunkId = ids[i];",
  157. `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`,
  158. Template.indent("installedChunks[chunkId][0]();"),
  159. "}",
  160. "installedChunks[ids[i]] = 0;"
  161. ]),
  162. "}",
  163. withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : ""
  164. ])}`
  165. : "// no install chunk",
  166. "",
  167. withLoading
  168. ? Template.asString([
  169. `${fn}.j = ${runtimeTemplate.basicFunction(
  170. "chunkId, promises",
  171. hasJsMatcher !== false
  172. ? Template.indent([
  173. "// import() chunk loading for javascript",
  174. `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`,
  175. 'if(installedChunkData !== 0) { // 0 means "already installed".',
  176. Template.indent([
  177. "",
  178. '// a Promise means "currently loading".',
  179. "if(installedChunkData) {",
  180. Template.indent([
  181. "promises.push(installedChunkData[1]);"
  182. ]),
  183. "} else {",
  184. Template.indent([
  185. hasJsMatcher === true
  186. ? "if(true) { // all chunks have JS"
  187. : `if(${hasJsMatcher("chunkId")}) {`,
  188. Template.indent([
  189. "// setup Promise in chunk cache",
  190. `var promise = ${importFunctionName}(${JSON.stringify(
  191. rootOutputDir
  192. )} + ${
  193. RuntimeGlobals.getChunkScriptFilename
  194. }(chunkId)).then(installChunk, ${runtimeTemplate.basicFunction(
  195. "e",
  196. [
  197. "if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;",
  198. "throw e;"
  199. ]
  200. )});`,
  201. `var promise = Promise.race([promise, new Promise(${runtimeTemplate.expressionFunction(
  202. `installedChunkData = installedChunks[chunkId] = [resolve]`,
  203. "resolve"
  204. )})])`,
  205. `promises.push(installedChunkData[1] = promise);`
  206. ]),
  207. hasJsMatcher === true
  208. ? "}"
  209. : "} else installedChunks[chunkId] = 0;"
  210. ]),
  211. "}"
  212. ]),
  213. "}"
  214. ])
  215. : Template.indent(["installedChunks[chunkId] = 0;"])
  216. )};`
  217. ])
  218. : "// no chunk on demand loading",
  219. "",
  220. withExternalInstallChunk
  221. ? Template.asString([
  222. `${RuntimeGlobals.externalInstallChunk} = installChunk;`
  223. ])
  224. : "// no external install chunk",
  225. "",
  226. withOnChunkLoad
  227. ? `${
  228. RuntimeGlobals.onChunksLoaded
  229. }.j = ${runtimeTemplate.returningFunction(
  230. "installedChunks[chunkId] === 0",
  231. "chunkId"
  232. )};`
  233. : "// no on chunks loaded"
  234. ]);
  235. }
  236. }
  237. module.exports = ModuleChunkLoadingRuntimeModule;