RequireChunkLoadingRuntimeModule.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. const RuntimeGlobals = require("../RuntimeGlobals");
  6. const RuntimeModule = require("../RuntimeModule");
  7. const Template = require("../Template");
  8. const {
  9. generateJavascriptHMR
  10. } = require("../hmr/JavascriptHotModuleReplacementHelper");
  11. const {
  12. chunkHasJs,
  13. getChunkFilenameTemplate
  14. } = require("../javascript/JavascriptModulesPlugin");
  15. const { getInitialChunkIds } = require("../javascript/StartupHelpers");
  16. const compileBooleanMatcher = require("../util/compileBooleanMatcher");
  17. const { getUndoPath } = require("../util/identifier");
  18. /** @typedef {import("../Chunk")} Chunk */
  19. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  20. /** @typedef {import("../Compilation")} Compilation */
  21. /** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
  22. class RequireChunkLoadingRuntimeModule extends RuntimeModule {
  23. /**
  24. * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements
  25. */
  26. constructor(runtimeRequirements) {
  27. super("require chunk loading", RuntimeModule.STAGE_ATTACH);
  28. this.runtimeRequirements = runtimeRequirements;
  29. }
  30. /**
  31. * @private
  32. * @param {Chunk} chunk chunk
  33. * @param {string} rootOutputDir root output directory
  34. * @returns {string} generated code
  35. */
  36. _generateBaseUri(chunk, rootOutputDir) {
  37. const options = chunk.getEntryOptions();
  38. if (options && options.baseUri) {
  39. return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`;
  40. }
  41. return `${RuntimeGlobals.baseURI} = require("url").pathToFileURL(${
  42. rootOutputDir !== "./"
  43. ? `__dirname + ${JSON.stringify(`/${rootOutputDir}`)}`
  44. : "__filename"
  45. });`;
  46. }
  47. /**
  48. * @returns {string | null} runtime code
  49. */
  50. generate() {
  51. const compilation = /** @type {Compilation} */ (this.compilation);
  52. const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
  53. const chunk = /** @type {Chunk} */ (this.chunk);
  54. const { runtimeTemplate } = compilation;
  55. const fn = RuntimeGlobals.ensureChunkHandlers;
  56. const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI);
  57. const withExternalInstallChunk = this.runtimeRequirements.has(
  58. RuntimeGlobals.externalInstallChunk
  59. );
  60. const withOnChunkLoad = this.runtimeRequirements.has(
  61. RuntimeGlobals.onChunksLoaded
  62. );
  63. const withLoading = this.runtimeRequirements.has(
  64. RuntimeGlobals.ensureChunkHandlers
  65. );
  66. const withHmr = this.runtimeRequirements.has(
  67. RuntimeGlobals.hmrDownloadUpdateHandlers
  68. );
  69. const withHmrManifest = this.runtimeRequirements.has(
  70. RuntimeGlobals.hmrDownloadManifest
  71. );
  72. const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs);
  73. const hasJsMatcher = compileBooleanMatcher(conditionMap);
  74. const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs);
  75. const outputName = compilation.getPath(
  76. getChunkFilenameTemplate(chunk, compilation.outputOptions),
  77. {
  78. chunk,
  79. contentHashType: "javascript"
  80. }
  81. );
  82. const rootOutputDir = getUndoPath(
  83. outputName,
  84. /** @type {string} */ (compilation.outputOptions.path),
  85. true
  86. );
  87. const stateExpression = withHmr
  88. ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_require`
  89. : undefined;
  90. return Template.asString([
  91. withBaseURI
  92. ? this._generateBaseUri(chunk, rootOutputDir)
  93. : "// no baseURI",
  94. "",
  95. "// object to store loaded chunks",
  96. '// "1" means "loaded", otherwise not loaded yet',
  97. `var installedChunks = ${
  98. stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
  99. }{`,
  100. Template.indent(
  101. Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 1`).join(
  102. ",\n"
  103. )
  104. ),
  105. "};",
  106. "",
  107. withOnChunkLoad
  108. ? `${
  109. RuntimeGlobals.onChunksLoaded
  110. }.require = ${runtimeTemplate.returningFunction(
  111. "installedChunks[chunkId]",
  112. "chunkId"
  113. )};`
  114. : "// no on chunks loaded",
  115. "",
  116. withLoading || withExternalInstallChunk
  117. ? `var installChunk = ${runtimeTemplate.basicFunction("chunk", [
  118. "var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;",
  119. "for(var moduleId in moreModules) {",
  120. Template.indent([
  121. `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
  122. Template.indent([
  123. `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];`
  124. ]),
  125. "}"
  126. ]),
  127. "}",
  128. `if(runtime) runtime(${RuntimeGlobals.require});`,
  129. "for(var i = 0; i < chunkIds.length; i++)",
  130. Template.indent("installedChunks[chunkIds[i]] = 1;"),
  131. withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : ""
  132. ])};`
  133. : "// no chunk install function needed",
  134. "",
  135. withLoading
  136. ? Template.asString([
  137. "// require() chunk loading for javascript",
  138. `${fn}.require = ${runtimeTemplate.basicFunction(
  139. "chunkId, promises",
  140. hasJsMatcher !== false
  141. ? [
  142. '// "1" is the signal for "already loaded"',
  143. "if(!installedChunks[chunkId]) {",
  144. Template.indent([
  145. hasJsMatcher === true
  146. ? "if(true) { // all chunks have JS"
  147. : `if(${hasJsMatcher("chunkId")}) {`,
  148. Template.indent([
  149. `installChunk(require(${JSON.stringify(
  150. rootOutputDir
  151. )} + ${
  152. RuntimeGlobals.getChunkScriptFilename
  153. }(chunkId)));`
  154. ]),
  155. "} else installedChunks[chunkId] = 1;",
  156. ""
  157. ]),
  158. "}"
  159. ]
  160. : "installedChunks[chunkId] = 1;"
  161. )};`
  162. ])
  163. : "// no chunk loading",
  164. "",
  165. withExternalInstallChunk
  166. ? Template.asString([
  167. `module.exports = ${RuntimeGlobals.require};`,
  168. `${RuntimeGlobals.externalInstallChunk} = installChunk;`
  169. ])
  170. : "// no external install chunk",
  171. "",
  172. withHmr
  173. ? Template.asString([
  174. "function loadUpdateChunk(chunkId, updatedModulesList) {",
  175. Template.indent([
  176. `var update = require(${JSON.stringify(rootOutputDir)} + ${
  177. RuntimeGlobals.getChunkUpdateScriptFilename
  178. }(chunkId));`,
  179. "var updatedModules = update.modules;",
  180. "var runtime = update.runtime;",
  181. "for(var moduleId in updatedModules) {",
  182. Template.indent([
  183. `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`,
  184. Template.indent([
  185. "currentUpdate[moduleId] = updatedModules[moduleId];",
  186. "if(updatedModulesList) updatedModulesList.push(moduleId);"
  187. ]),
  188. "}"
  189. ]),
  190. "}",
  191. "if(runtime) currentUpdateRuntime.push(runtime);"
  192. ]),
  193. "}",
  194. "",
  195. generateJavascriptHMR("require")
  196. ])
  197. : "// no HMR",
  198. "",
  199. withHmrManifest
  200. ? Template.asString([
  201. `${RuntimeGlobals.hmrDownloadManifest} = function() {`,
  202. Template.indent([
  203. "return Promise.resolve().then(function() {",
  204. Template.indent([
  205. `return require(${JSON.stringify(rootOutputDir)} + ${
  206. RuntimeGlobals.getUpdateManifestFilename
  207. }());`
  208. ]),
  209. "})['catch'](function(err) { if(err.code !== 'MODULE_NOT_FOUND') throw err; });"
  210. ]),
  211. "}"
  212. ])
  213. : "// no HMR manifest"
  214. ]);
  215. }
  216. }
  217. module.exports = RequireChunkLoadingRuntimeModule;