ReadFileChunkLoadingRuntimeModule.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  17. /** @typedef {import("../Compilation")} Compilation */
  18. class ReadFileChunkLoadingRuntimeModule extends RuntimeModule {
  19. /**
  20. * @param {ReadonlySet<string>} runtimeRequirements runtime requirements
  21. */
  22. constructor(runtimeRequirements) {
  23. super("readFile chunk loading", RuntimeModule.STAGE_ATTACH);
  24. this.runtimeRequirements = runtimeRequirements;
  25. }
  26. /**
  27. * @private
  28. * @param {Chunk} chunk chunk
  29. * @param {string} rootOutputDir root output directory
  30. * @returns {string} generated code
  31. */
  32. _generateBaseUri(chunk, rootOutputDir) {
  33. const options = chunk.getEntryOptions();
  34. if (options && options.baseUri) {
  35. return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`;
  36. }
  37. return `${RuntimeGlobals.baseURI} = require("url").pathToFileURL(${
  38. rootOutputDir
  39. ? `__dirname + ${JSON.stringify("/" + rootOutputDir)}`
  40. : "__filename"
  41. });`;
  42. }
  43. /**
  44. * @returns {string | null} runtime code
  45. */
  46. generate() {
  47. const compilation = /** @type {Compilation} */ (this.compilation);
  48. const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
  49. const chunk = /** @type {Chunk} */ (this.chunk);
  50. const { runtimeTemplate } = compilation;
  51. const fn = RuntimeGlobals.ensureChunkHandlers;
  52. const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI);
  53. const withExternalInstallChunk = this.runtimeRequirements.has(
  54. RuntimeGlobals.externalInstallChunk
  55. );
  56. const withOnChunkLoad = this.runtimeRequirements.has(
  57. RuntimeGlobals.onChunksLoaded
  58. );
  59. const withLoading = this.runtimeRequirements.has(
  60. RuntimeGlobals.ensureChunkHandlers
  61. );
  62. const withHmr = this.runtimeRequirements.has(
  63. RuntimeGlobals.hmrDownloadUpdateHandlers
  64. );
  65. const withHmrManifest = this.runtimeRequirements.has(
  66. RuntimeGlobals.hmrDownloadManifest
  67. );
  68. const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs);
  69. const hasJsMatcher = compileBooleanMatcher(conditionMap);
  70. const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs);
  71. const outputName = compilation.getPath(
  72. getChunkFilenameTemplate(chunk, compilation.outputOptions),
  73. {
  74. chunk,
  75. contentHashType: "javascript"
  76. }
  77. );
  78. const rootOutputDir = getUndoPath(
  79. outputName,
  80. /** @type {string} */ (compilation.outputOptions.path),
  81. false
  82. );
  83. const stateExpression = withHmr
  84. ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_readFileVm`
  85. : undefined;
  86. return Template.asString([
  87. withBaseURI
  88. ? this._generateBaseUri(chunk, rootOutputDir)
  89. : "// no baseURI",
  90. "",
  91. "// object to store loaded chunks",
  92. '// "0" means "already loaded", Promise means loading',
  93. `var installedChunks = ${
  94. stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
  95. }{`,
  96. Template.indent(
  97. Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join(
  98. ",\n"
  99. )
  100. ),
  101. "};",
  102. "",
  103. withOnChunkLoad
  104. ? `${
  105. RuntimeGlobals.onChunksLoaded
  106. }.readFileVm = ${runtimeTemplate.returningFunction(
  107. "installedChunks[chunkId] === 0",
  108. "chunkId"
  109. )};`
  110. : "// no on chunks loaded",
  111. "",
  112. withLoading || withExternalInstallChunk
  113. ? `var installChunk = ${runtimeTemplate.basicFunction("chunk", [
  114. "var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;",
  115. "for(var moduleId in moreModules) {",
  116. Template.indent([
  117. `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
  118. Template.indent([
  119. `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];`
  120. ]),
  121. "}"
  122. ]),
  123. "}",
  124. `if(runtime) runtime(${RuntimeGlobals.require});`,
  125. "for(var i = 0; i < chunkIds.length; i++) {",
  126. Template.indent([
  127. "if(installedChunks[chunkIds[i]]) {",
  128. Template.indent(["installedChunks[chunkIds[i]][0]();"]),
  129. "}",
  130. "installedChunks[chunkIds[i]] = 0;"
  131. ]),
  132. "}",
  133. withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : ""
  134. ])};`
  135. : "// no chunk install function needed",
  136. "",
  137. withLoading
  138. ? Template.asString([
  139. "// ReadFile + VM.run chunk loading for javascript",
  140. `${fn}.readFileVm = function(chunkId, promises) {`,
  141. hasJsMatcher !== false
  142. ? Template.indent([
  143. "",
  144. "var installedChunkData = installedChunks[chunkId];",
  145. 'if(installedChunkData !== 0) { // 0 means "already installed".',
  146. Template.indent([
  147. '// array of [resolve, reject, promise] means "currently loading"',
  148. "if(installedChunkData) {",
  149. Template.indent(["promises.push(installedChunkData[2]);"]),
  150. "} else {",
  151. Template.indent([
  152. hasJsMatcher === true
  153. ? "if(true) { // all chunks have JS"
  154. : `if(${hasJsMatcher("chunkId")}) {`,
  155. Template.indent([
  156. "// load the chunk and return promise to it",
  157. "var promise = new Promise(function(resolve, reject) {",
  158. Template.indent([
  159. "installedChunkData = installedChunks[chunkId] = [resolve, reject];",
  160. `var filename = require('path').join(__dirname, ${JSON.stringify(
  161. rootOutputDir
  162. )} + ${
  163. RuntimeGlobals.getChunkScriptFilename
  164. }(chunkId));`,
  165. "require('fs').readFile(filename, 'utf-8', function(err, content) {",
  166. Template.indent([
  167. "if(err) return reject(err);",
  168. "var chunk = {};",
  169. "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" +
  170. "(chunk, require, require('path').dirname(filename), filename);",
  171. "installChunk(chunk);"
  172. ]),
  173. "});"
  174. ]),
  175. "});",
  176. "promises.push(installedChunkData[2] = promise);"
  177. ]),
  178. hasJsMatcher === true
  179. ? "}"
  180. : "} else installedChunks[chunkId] = 0;"
  181. ]),
  182. "}"
  183. ]),
  184. "}"
  185. ])
  186. : Template.indent(["installedChunks[chunkId] = 0;"]),
  187. "};"
  188. ])
  189. : "// no chunk loading",
  190. "",
  191. withExternalInstallChunk
  192. ? Template.asString([
  193. `module.exports = ${RuntimeGlobals.require};`,
  194. `${RuntimeGlobals.externalInstallChunk} = installChunk;`
  195. ])
  196. : "// no external install chunk",
  197. "",
  198. withHmr
  199. ? Template.asString([
  200. "function loadUpdateChunk(chunkId, updatedModulesList) {",
  201. Template.indent([
  202. "return new Promise(function(resolve, reject) {",
  203. Template.indent([
  204. `var filename = require('path').join(__dirname, ${JSON.stringify(
  205. rootOutputDir
  206. )} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId));`,
  207. "require('fs').readFile(filename, 'utf-8', function(err, content) {",
  208. Template.indent([
  209. "if(err) return reject(err);",
  210. "var update = {};",
  211. "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" +
  212. "(update, require, require('path').dirname(filename), filename);",
  213. "var updatedModules = update.modules;",
  214. "var runtime = update.runtime;",
  215. "for(var moduleId in updatedModules) {",
  216. Template.indent([
  217. `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`,
  218. Template.indent([
  219. `currentUpdate[moduleId] = updatedModules[moduleId];`,
  220. "if(updatedModulesList) updatedModulesList.push(moduleId);"
  221. ]),
  222. "}"
  223. ]),
  224. "}",
  225. "if(runtime) currentUpdateRuntime.push(runtime);",
  226. "resolve();"
  227. ]),
  228. "});"
  229. ]),
  230. "});"
  231. ]),
  232. "}",
  233. "",
  234. Template.getFunctionContent(
  235. require("../hmr/JavascriptHotModuleReplacement.runtime.js")
  236. )
  237. .replace(/\$key\$/g, "readFileVm")
  238. .replace(/\$installedChunks\$/g, "installedChunks")
  239. .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk")
  240. .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache)
  241. .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories)
  242. .replace(
  243. /\$ensureChunkHandlers\$/g,
  244. RuntimeGlobals.ensureChunkHandlers
  245. )
  246. .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty)
  247. .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData)
  248. .replace(
  249. /\$hmrDownloadUpdateHandlers\$/g,
  250. RuntimeGlobals.hmrDownloadUpdateHandlers
  251. )
  252. .replace(
  253. /\$hmrInvalidateModuleHandlers\$/g,
  254. RuntimeGlobals.hmrInvalidateModuleHandlers
  255. )
  256. ])
  257. : "// no HMR",
  258. "",
  259. withHmrManifest
  260. ? Template.asString([
  261. `${RuntimeGlobals.hmrDownloadManifest} = function() {`,
  262. Template.indent([
  263. "return new Promise(function(resolve, reject) {",
  264. Template.indent([
  265. `var filename = require('path').join(__dirname, ${JSON.stringify(
  266. rootOutputDir
  267. )} + ${RuntimeGlobals.getUpdateManifestFilename}());`,
  268. "require('fs').readFile(filename, 'utf-8', function(err, content) {",
  269. Template.indent([
  270. "if(err) {",
  271. Template.indent([
  272. 'if(err.code === "ENOENT") return resolve();',
  273. "return reject(err);"
  274. ]),
  275. "}",
  276. "try { resolve(JSON.parse(content)); }",
  277. "catch(e) { reject(e); }"
  278. ]),
  279. "});"
  280. ]),
  281. "});"
  282. ]),
  283. "}"
  284. ])
  285. : "// no HMR manifest"
  286. ]);
  287. }
  288. }
  289. module.exports = ReadFileChunkLoadingRuntimeModule;