RequireChunkLoadingRuntimeModule.js 7.4 KB

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