EnsureChunkRuntimeModule.js 1.7 KB

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