RequireChunkLoadingRuntimeModule.js 7.6 KB

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