ImportScriptsChunkLoadingRuntimeModule.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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 ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule {
  23. /**
  24. * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements
  25. * @param {boolean} withCreateScriptUrl with createScriptUrl support
  26. */
  27. constructor(runtimeRequirements, withCreateScriptUrl) {
  28. super("importScripts chunk loading", RuntimeModule.STAGE_ATTACH);
  29. /** @type {ReadOnlyRuntimeRequirements} */
  30. this.runtimeRequirements = runtimeRequirements;
  31. /** @type {boolean} */
  32. this._withCreateScriptUrl = withCreateScriptUrl;
  33. }
  34. /**
  35. * @private
  36. * @param {Chunk} chunk chunk
  37. * @returns {string} generated code
  38. */
  39. _generateBaseUri(chunk) {
  40. const options = chunk.getEntryOptions();
  41. if (options && options.baseUri) {
  42. return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`;
  43. }
  44. const compilation = /** @type {Compilation} */ (this.compilation);
  45. const outputName = compilation.getPath(
  46. getChunkFilenameTemplate(chunk, compilation.outputOptions),
  47. {
  48. chunk,
  49. contentHashType: "javascript"
  50. }
  51. );
  52. const rootOutputDir = getUndoPath(
  53. outputName,
  54. compilation.outputOptions.path,
  55. false
  56. );
  57. return `${RuntimeGlobals.baseURI} = self.location + ${JSON.stringify(
  58. rootOutputDir ? `/../${rootOutputDir}` : ""
  59. )};`;
  60. }
  61. /**
  62. * Generates runtime code for this runtime module.
  63. * @returns {string | null} runtime code
  64. */
  65. generate() {
  66. const compilation = /** @type {Compilation} */ (this.compilation);
  67. const fn = RuntimeGlobals.ensureChunkHandlers;
  68. const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI);
  69. const withLoading = this.runtimeRequirements.has(
  70. RuntimeGlobals.ensureChunkHandlers
  71. );
  72. const withCallback = this.runtimeRequirements.has(
  73. RuntimeGlobals.chunkCallback
  74. );
  75. const withHmr = this.runtimeRequirements.has(
  76. RuntimeGlobals.hmrDownloadUpdateHandlers
  77. );
  78. const withHmrManifest = this.runtimeRequirements.has(
  79. RuntimeGlobals.hmrDownloadManifest
  80. );
  81. const globalObject = compilation.runtimeTemplate.globalObject;
  82. const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify(
  83. compilation.outputOptions.chunkLoadingGlobal
  84. )}]`;
  85. const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
  86. const chunk = /** @type {Chunk} */ (this.chunk);
  87. const hasJsMatcher = compileBooleanMatcher(
  88. chunkGraph.getChunkConditionMap(chunk, chunkHasJs)
  89. );
  90. const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs);
  91. const stateExpression = withHmr
  92. ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_importScripts`
  93. : undefined;
  94. const runtimeTemplate = compilation.runtimeTemplate;
  95. const { _withCreateScriptUrl: withCreateScriptUrl } = this;
  96. return Template.asString([
  97. withBaseURI ? this._generateBaseUri(chunk) : "// no baseURI",
  98. "",
  99. "// object to store loaded chunks",
  100. '// "1" means "already loaded"',
  101. `var installedChunks = ${
  102. stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
  103. }{`,
  104. Template.indent(
  105. Array.from(initialChunkIds, (id) => `${JSON.stringify(id)}: 1`).join(
  106. ",\n"
  107. )
  108. ),
  109. "};",
  110. "",
  111. withCallback || withLoading
  112. ? Template.asString([
  113. "// importScripts chunk loading",
  114. `var installChunk = ${runtimeTemplate.basicFunction("data", [
  115. runtimeTemplate.destructureArray(
  116. ["chunkIds", "moreModules", "runtime"],
  117. "data"
  118. ),
  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. "while(chunkIds.length)",
  130. Template.indent("installedChunks[chunkIds.pop()] = 1;"),
  131. "parentChunkLoadingFunction(data);"
  132. ])};`
  133. ])
  134. : "// no chunk install function needed",
  135. withCallback || withLoading
  136. ? Template.asString([
  137. withLoading
  138. ? `${fn}.i = ${runtimeTemplate.basicFunction(
  139. "chunkId, promises",
  140. hasJsMatcher !== false
  141. ? [
  142. '// "1" is the signal for "already loaded"',
  143. "if(!installedChunks[chunkId]) {",
  144. Template.indent([
  145. hasJsMatcher === true
  146. ? "if(true) { // all chunks have JS"
  147. : `if(${hasJsMatcher("chunkId")}) {`,
  148. Template.indent(
  149. `importScripts(${
  150. withCreateScriptUrl
  151. ? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId))`
  152. : `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId)`
  153. });`
  154. ),
  155. "}"
  156. ]),
  157. "}"
  158. ]
  159. : "installedChunks[chunkId] = 1;"
  160. )};`
  161. : "",
  162. "",
  163. `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`,
  164. "var parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);",
  165. "chunkLoadingGlobal.push = installChunk;"
  166. ])
  167. : "// no chunk loading",
  168. "",
  169. withHmr
  170. ? Template.asString([
  171. "function loadUpdateChunk(chunkId, updatedModulesList) {",
  172. Template.indent([
  173. "var success = false;",
  174. `${globalObject}[${JSON.stringify(
  175. compilation.outputOptions.hotUpdateGlobal
  176. )}] = ${runtimeTemplate.basicFunction("_, moreModules, runtime", [
  177. "for(var moduleId in moreModules) {",
  178. Template.indent([
  179. `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
  180. Template.indent([
  181. "currentUpdate[moduleId] = moreModules[moduleId];",
  182. "if(updatedModulesList) updatedModulesList.push(moduleId);"
  183. ]),
  184. "}"
  185. ]),
  186. "}",
  187. "if(runtime) currentUpdateRuntime.push(runtime);",
  188. "success = true;"
  189. ])};`,
  190. "// start update chunk loading",
  191. `importScripts(${
  192. withCreateScriptUrl
  193. ? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId))`
  194. : `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId)`
  195. });`,
  196. 'if(!success) throw new Error("Loading update chunk failed for unknown reason");'
  197. ]),
  198. "}",
  199. "",
  200. generateJavascriptHMR("importScripts")
  201. ])
  202. : "// no HMR",
  203. "",
  204. withHmrManifest
  205. ? Template.asString([
  206. `${
  207. RuntimeGlobals.hmrDownloadManifest
  208. } = ${runtimeTemplate.basicFunction("", [
  209. 'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");',
  210. `return fetch(${RuntimeGlobals.publicPath} + ${
  211. RuntimeGlobals.getUpdateManifestFilename
  212. }()).then(${runtimeTemplate.basicFunction("response", [
  213. "if(response.status === 404) return; // no update available",
  214. 'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);',
  215. "return response.json();"
  216. ])});`
  217. ])};`
  218. ])
  219. : "// no HMR manifest"
  220. ]);
  221. }
  222. }
  223. module.exports = ImportScriptsChunkLoadingRuntimeModule;