ImportScriptsChunkLoadingRuntimeModule.js 8.6 KB

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