StartupChunkDependenciesRuntimeModule.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const RuntimeGlobals = require("../RuntimeGlobals");
  7. const RuntimeModule = require("../RuntimeModule");
  8. const Template = require("../Template");
  9. /** @typedef {import("../Chunk")} Chunk */
  10. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  11. /** @typedef {import("../Compilation")} Compilation */
  12. class StartupChunkDependenciesRuntimeModule extends RuntimeModule {
  13. /**
  14. * @param {boolean} asyncChunkLoading use async chunk loading
  15. */
  16. constructor(asyncChunkLoading) {
  17. super("startup chunk dependencies", RuntimeModule.STAGE_TRIGGER);
  18. /** @type {boolean} */
  19. this.asyncChunkLoading = asyncChunkLoading;
  20. }
  21. /**
  22. * Generates runtime code for this runtime module.
  23. * @returns {string | null} runtime code
  24. */
  25. generate() {
  26. const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
  27. const chunk = /** @type {Chunk} */ (this.chunk);
  28. const chunkIds = [
  29. ...chunkGraph.getChunkEntryDependentChunksIterable(chunk)
  30. ].map((chunk) => chunk.id);
  31. const compilation = /** @type {Compilation} */ (this.compilation);
  32. const { runtimeTemplate } = compilation;
  33. return Template.asString([
  34. `var next = ${RuntimeGlobals.startup};`,
  35. `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction(
  36. "",
  37. !this.asyncChunkLoading
  38. ? [
  39. ...chunkIds.map(
  40. (id) => `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)});`
  41. ),
  42. "return next();"
  43. ]
  44. : chunkIds.length === 1
  45. ? `return ${RuntimeGlobals.ensureChunk}(${JSON.stringify(
  46. chunkIds[0]
  47. )}).then(next);`
  48. : chunkIds.length > 2
  49. ? [
  50. // using map is shorter for 3 or more chunks
  51. `return Promise.all(${JSON.stringify(chunkIds)}.map(${
  52. RuntimeGlobals.ensureChunk
  53. }, ${RuntimeGlobals.require})).then(next);`
  54. ]
  55. : [
  56. // calling ensureChunk directly is shorter for 0 - 2 chunks
  57. "return Promise.all([",
  58. Template.indent(
  59. chunkIds
  60. .map(
  61. (id) =>
  62. `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)})`
  63. )
  64. .join(",\n")
  65. ),
  66. "]).then(next);"
  67. ]
  68. )};`
  69. ]);
  70. }
  71. }
  72. module.exports = StartupChunkDependenciesRuntimeModule;