ReadFileChunkLoadingRuntimeModule.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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 ReadFileChunkLoadingRuntimeModule extends RuntimeModule {
  16. constructor(runtimeRequirements) {
  17. super("readFile 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. false
  57. );
  58. const stateExpression = withHmr
  59. ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_readFileVm`
  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. '// "0" means "already loaded", Promise means loading',
  74. `var installedChunks = ${
  75. stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
  76. }{`,
  77. Template.indent(
  78. Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join(
  79. ",\n"
  80. )
  81. ),
  82. "};",
  83. "",
  84. withOnChunkLoad
  85. ? `${
  86. RuntimeGlobals.onChunksLoaded
  87. }.readFileVm = ${runtimeTemplate.returningFunction(
  88. "installedChunks[chunkId] === 0",
  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([
  108. "if(installedChunks[chunkIds[i]]) {",
  109. Template.indent(["installedChunks[chunkIds[i]][0]();"]),
  110. "}",
  111. "installedChunks[chunkIds[i]] = 0;"
  112. ]),
  113. "}",
  114. withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : ""
  115. ])};`
  116. : "// no chunk install function needed",
  117. "",
  118. withLoading
  119. ? Template.asString([
  120. "// ReadFile + VM.run chunk loading for javascript",
  121. `${fn}.readFileVm = function(chunkId, promises) {`,
  122. hasJsMatcher !== false
  123. ? Template.indent([
  124. "",
  125. "var installedChunkData = installedChunks[chunkId];",
  126. 'if(installedChunkData !== 0) { // 0 means "already installed".',
  127. Template.indent([
  128. '// array of [resolve, reject, promise] means "currently loading"',
  129. "if(installedChunkData) {",
  130. Template.indent(["promises.push(installedChunkData[2]);"]),
  131. "} else {",
  132. Template.indent([
  133. hasJsMatcher === true
  134. ? "if(true) { // all chunks have JS"
  135. : `if(${hasJsMatcher("chunkId")}) {`,
  136. Template.indent([
  137. "// load the chunk and return promise to it",
  138. "var promise = new Promise(function(resolve, reject) {",
  139. Template.indent([
  140. "installedChunkData = installedChunks[chunkId] = [resolve, reject];",
  141. `var filename = require('path').join(__dirname, ${JSON.stringify(
  142. rootOutputDir
  143. )} + ${
  144. RuntimeGlobals.getChunkScriptFilename
  145. }(chunkId));`,
  146. "require('fs').readFile(filename, 'utf-8', function(err, content) {",
  147. Template.indent([
  148. "if(err) return reject(err);",
  149. "var chunk = {};",
  150. "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" +
  151. "(chunk, require, require('path').dirname(filename), filename);",
  152. "installChunk(chunk);"
  153. ]),
  154. "});"
  155. ]),
  156. "});",
  157. "promises.push(installedChunkData[2] = promise);"
  158. ]),
  159. "} else installedChunks[chunkId] = 0;"
  160. ]),
  161. "}"
  162. ]),
  163. "}"
  164. ])
  165. : Template.indent(["installedChunks[chunkId] = 0;"]),
  166. "};"
  167. ])
  168. : "// no chunk loading",
  169. "",
  170. withExternalInstallChunk
  171. ? Template.asString([
  172. "module.exports = __webpack_require__;",
  173. `${RuntimeGlobals.externalInstallChunk} = installChunk;`
  174. ])
  175. : "// no external install chunk",
  176. "",
  177. withHmr
  178. ? Template.asString([
  179. "function loadUpdateChunk(chunkId, updatedModulesList) {",
  180. Template.indent([
  181. "return new Promise(function(resolve, reject) {",
  182. Template.indent([
  183. `var filename = require('path').join(__dirname, ${JSON.stringify(
  184. rootOutputDir
  185. )} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId));`,
  186. "require('fs').readFile(filename, 'utf-8', function(err, content) {",
  187. Template.indent([
  188. "if(err) return reject(err);",
  189. "var update = {};",
  190. "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" +
  191. "(update, require, require('path').dirname(filename), filename);",
  192. "var updatedModules = update.modules;",
  193. "var runtime = update.runtime;",
  194. "for(var moduleId in updatedModules) {",
  195. Template.indent([
  196. `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`,
  197. Template.indent([
  198. `currentUpdate[moduleId] = updatedModules[moduleId];`,
  199. "if(updatedModulesList) updatedModulesList.push(moduleId);"
  200. ]),
  201. "}"
  202. ]),
  203. "}",
  204. "if(runtime) currentUpdateRuntime.push(runtime);",
  205. "resolve();"
  206. ]),
  207. "});"
  208. ]),
  209. "});"
  210. ]),
  211. "}",
  212. "",
  213. Template.getFunctionContent(
  214. require("../hmr/JavascriptHotModuleReplacement.runtime.js")
  215. )
  216. .replace(/\$key\$/g, "readFileVm")
  217. .replace(/\$installedChunks\$/g, "installedChunks")
  218. .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk")
  219. .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache)
  220. .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories)
  221. .replace(
  222. /\$ensureChunkHandlers\$/g,
  223. RuntimeGlobals.ensureChunkHandlers
  224. )
  225. .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty)
  226. .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData)
  227. .replace(
  228. /\$hmrDownloadUpdateHandlers\$/g,
  229. RuntimeGlobals.hmrDownloadUpdateHandlers
  230. )
  231. .replace(
  232. /\$hmrInvalidateModuleHandlers\$/g,
  233. RuntimeGlobals.hmrInvalidateModuleHandlers
  234. )
  235. ])
  236. : "// no HMR",
  237. "",
  238. withHmrManifest
  239. ? Template.asString([
  240. `${RuntimeGlobals.hmrDownloadManifest} = function() {`,
  241. Template.indent([
  242. "return new Promise(function(resolve, reject) {",
  243. Template.indent([
  244. `var filename = require('path').join(__dirname, ${JSON.stringify(
  245. rootOutputDir
  246. )} + ${RuntimeGlobals.getUpdateManifestFilename}());`,
  247. "require('fs').readFile(filename, 'utf-8', function(err, content) {",
  248. Template.indent([
  249. "if(err) {",
  250. Template.indent([
  251. 'if(err.code === "ENOENT") return resolve();',
  252. "return reject(err);"
  253. ]),
  254. "}",
  255. "try { resolve(JSON.parse(content)); }",
  256. "catch(e) { reject(e); }"
  257. ]),
  258. "});"
  259. ]),
  260. "});"
  261. ]),
  262. "}"
  263. ])
  264. : "// no HMR manifest"
  265. ]);
  266. }
  267. }
  268. module.exports = ReadFileChunkLoadingRuntimeModule;