EnsureChunkRuntimeModule.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. /** @typedef {import("../Compilation")} Compilation */
  9. class EnsureChunkRuntimeModule extends RuntimeModule {
  10. /**
  11. * @param {ReadonlySet<string>} runtimeRequirements runtime requirements
  12. */
  13. constructor(runtimeRequirements) {
  14. super("ensure chunk");
  15. this.runtimeRequirements = runtimeRequirements;
  16. }
  17. /**
  18. * @returns {string | null} runtime code
  19. */
  20. generate() {
  21. const compilation = /** @type {Compilation} */ (this.compilation);
  22. const { runtimeTemplate } = compilation;
  23. // Check if there are non initial chunks which need to be imported using require-ensure
  24. if (this.runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers)) {
  25. const withFetchPriority = this.runtimeRequirements.has(
  26. RuntimeGlobals.hasFetchPriority
  27. );
  28. const handlers = RuntimeGlobals.ensureChunkHandlers;
  29. return Template.asString([
  30. `${handlers} = {};`,
  31. "// This file contains only the entry chunk.",
  32. "// The chunk loading function for additional chunks",
  33. `${RuntimeGlobals.ensureChunk} = ${runtimeTemplate.basicFunction(
  34. `chunkId${withFetchPriority ? ", fetchPriority" : ""}`,
  35. [
  36. `return Promise.all(Object.keys(${handlers}).reduce(${runtimeTemplate.basicFunction(
  37. "promises, key",
  38. [
  39. `${handlers}[key](chunkId, promises${
  40. withFetchPriority ? ", fetchPriority" : ""
  41. });`,
  42. "return promises;"
  43. ]
  44. )}, []));`
  45. ]
  46. )};`
  47. ]);
  48. } else {
  49. // There ensureChunk is used somewhere in the tree, so we need an empty requireEnsure
  50. // function. This can happen with multiple entrypoints.
  51. return Template.asString([
  52. "// The chunk loading function for additional chunks",
  53. "// Since all referenced chunks are already included",
  54. "// in this file, this function is empty here.",
  55. `${RuntimeGlobals.ensureChunk} = ${runtimeTemplate.returningFunction(
  56. "Promise.resolve()"
  57. )};`
  58. ]);
  59. }
  60. }
  61. }
  62. module.exports = EnsureChunkRuntimeModule;