ImportScriptsChunkLoadingRuntimeModule.js 7.8 KB

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