ReadFileChunkLoadingRuntimeModule.js 10 KB

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