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