ReadFileChunkLoadingRuntimeModule.js 9.3 KB

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