ReadFileChunkLoadingRuntimeModule.js 10 KB

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