RequireChunkLoadingRuntimeModule.js 7.7 KB

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