RequireChunkLoadingRuntimeModule.js 7.7 KB

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