RequireChunkLoadingRuntimeModule.js 7.8 KB

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