ReadFileChunkLoadingRuntimeModule.js 9.6 KB

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