EnsureChunkRuntimeModule.js 2.3 KB

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