ImportScriptsChunkLoadingRuntimeModule.js 7.9 KB

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