ReadFileChunkLoadingRuntimeModule.js 10 KB

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