ImportScriptsChunkLoadingRuntimeModule.js 8.3 KB

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