RequireChunkLoadingRuntimeModule.js 7.0 KB

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