EnsureChunkRuntimeModule.js 2.3 KB

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