ReadFileChunkLoadingRuntimeModule.js 10 KB

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