ImportScriptsChunkLoadingRuntimeModule.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. * @returns {string | null} runtime code
  63. */
  64. generate() {
  65. const compilation = /** @type {Compilation} */ (this.compilation);
  66. const fn = RuntimeGlobals.ensureChunkHandlers;
  67. const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI);
  68. const withLoading = this.runtimeRequirements.has(
  69. RuntimeGlobals.ensureChunkHandlers
  70. );
  71. const withCallback = this.runtimeRequirements.has(
  72. RuntimeGlobals.chunkCallback
  73. );
  74. const withHmr = this.runtimeRequirements.has(
  75. RuntimeGlobals.hmrDownloadUpdateHandlers
  76. );
  77. const withHmrManifest = this.runtimeRequirements.has(
  78. RuntimeGlobals.hmrDownloadManifest
  79. );
  80. const globalObject = compilation.runtimeTemplate.globalObject;
  81. const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify(
  82. compilation.outputOptions.chunkLoadingGlobal
  83. )}]`;
  84. const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
  85. const chunk = /** @type {Chunk} */ (this.chunk);
  86. const hasJsMatcher = compileBooleanMatcher(
  87. chunkGraph.getChunkConditionMap(chunk, chunkHasJs)
  88. );
  89. const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs);
  90. const stateExpression = withHmr
  91. ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_importScripts`
  92. : undefined;
  93. const runtimeTemplate = compilation.runtimeTemplate;
  94. const { _withCreateScriptUrl: withCreateScriptUrl } = this;
  95. return Template.asString([
  96. withBaseURI ? this._generateBaseUri(chunk) : "// no baseURI",
  97. "",
  98. "// object to store loaded chunks",
  99. '// "1" means "already loaded"',
  100. `var installedChunks = ${
  101. stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
  102. }{`,
  103. Template.indent(
  104. Array.from(initialChunkIds, (id) => `${JSON.stringify(id)}: 1`).join(
  105. ",\n"
  106. )
  107. ),
  108. "};",
  109. "",
  110. withCallback || withLoading
  111. ? Template.asString([
  112. "// importScripts chunk loading",
  113. `var installChunk = ${runtimeTemplate.basicFunction("data", [
  114. runtimeTemplate.destructureArray(
  115. ["chunkIds", "moreModules", "runtime"],
  116. "data"
  117. ),
  118. "for(var moduleId in moreModules) {",
  119. Template.indent([
  120. `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
  121. Template.indent(
  122. `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];`
  123. ),
  124. "}"
  125. ]),
  126. "}",
  127. `if(runtime) runtime(${RuntimeGlobals.require});`,
  128. "while(chunkIds.length)",
  129. Template.indent("installedChunks[chunkIds.pop()] = 1;"),
  130. "parentChunkLoadingFunction(data);"
  131. ])};`
  132. ])
  133. : "// no chunk install function needed",
  134. withCallback || withLoading
  135. ? Template.asString([
  136. withLoading
  137. ? `${fn}.i = ${runtimeTemplate.basicFunction(
  138. "chunkId, promises",
  139. hasJsMatcher !== false
  140. ? [
  141. '// "1" is the signal for "already loaded"',
  142. "if(!installedChunks[chunkId]) {",
  143. Template.indent([
  144. hasJsMatcher === true
  145. ? "if(true) { // all chunks have JS"
  146. : `if(${hasJsMatcher("chunkId")}) {`,
  147. Template.indent(
  148. `importScripts(${
  149. withCreateScriptUrl
  150. ? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId))`
  151. : `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId)`
  152. });`
  153. ),
  154. "}"
  155. ]),
  156. "}"
  157. ]
  158. : "installedChunks[chunkId] = 1;"
  159. )};`
  160. : "",
  161. "",
  162. `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`,
  163. "var parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);",
  164. "chunkLoadingGlobal.push = installChunk;"
  165. ])
  166. : "// no chunk loading",
  167. "",
  168. withHmr
  169. ? Template.asString([
  170. "function loadUpdateChunk(chunkId, updatedModulesList) {",
  171. Template.indent([
  172. "var success = false;",
  173. `${globalObject}[${JSON.stringify(
  174. compilation.outputOptions.hotUpdateGlobal
  175. )}] = ${runtimeTemplate.basicFunction("_, moreModules, runtime", [
  176. "for(var moduleId in moreModules) {",
  177. Template.indent([
  178. `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
  179. Template.indent([
  180. "currentUpdate[moduleId] = moreModules[moduleId];",
  181. "if(updatedModulesList) updatedModulesList.push(moduleId);"
  182. ]),
  183. "}"
  184. ]),
  185. "}",
  186. "if(runtime) currentUpdateRuntime.push(runtime);",
  187. "success = true;"
  188. ])};`,
  189. "// start update chunk loading",
  190. `importScripts(${
  191. withCreateScriptUrl
  192. ? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId))`
  193. : `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId)`
  194. });`,
  195. 'if(!success) throw new Error("Loading update chunk failed for unknown reason");'
  196. ]),
  197. "}",
  198. "",
  199. generateJavascriptHMR("importScripts")
  200. ])
  201. : "// no HMR",
  202. "",
  203. withHmrManifest
  204. ? Template.asString([
  205. `${
  206. RuntimeGlobals.hmrDownloadManifest
  207. } = ${runtimeTemplate.basicFunction("", [
  208. 'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");',
  209. `return fetch(${RuntimeGlobals.publicPath} + ${
  210. RuntimeGlobals.getUpdateManifestFilename
  211. }()).then(${runtimeTemplate.basicFunction("response", [
  212. "if(response.status === 404) return; // no update available",
  213. 'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);',
  214. "return response.json();"
  215. ])});`
  216. ])};`
  217. ])
  218. : "// no HMR manifest"
  219. ]);
  220. }
  221. }
  222. module.exports = ImportScriptsChunkLoadingRuntimeModule;