StartupChunkDependenciesRuntimeModule.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. this.asyncChunkLoading = asyncChunkLoading;
  19. }
  20. /**
  21. * @returns {string | null} runtime code
  22. */
  23. generate() {
  24. const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
  25. const chunk = /** @type {Chunk} */ (this.chunk);
  26. const chunkIds = Array.from(
  27. chunkGraph.getChunkEntryDependentChunksIterable(chunk)
  28. ).map(chunk => chunk.id);
  29. const compilation = /** @type {Compilation} */ (this.compilation);
  30. const { runtimeTemplate } = compilation;
  31. return Template.asString([
  32. `var next = ${RuntimeGlobals.startup};`,
  33. `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction(
  34. "",
  35. !this.asyncChunkLoading
  36. ? chunkIds
  37. .map(
  38. id => `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)});`
  39. )
  40. .concat("return next();")
  41. : chunkIds.length === 1
  42. ? `return ${RuntimeGlobals.ensureChunk}(${JSON.stringify(
  43. chunkIds[0]
  44. )}).then(next);`
  45. : chunkIds.length > 2
  46. ? [
  47. // using map is shorter for 3 or more chunks
  48. `return Promise.all(${JSON.stringify(chunkIds)}.map(${
  49. RuntimeGlobals.ensureChunk
  50. }, ${RuntimeGlobals.require})).then(next);`
  51. ]
  52. : [
  53. // calling ensureChunk directly is shorter for 0 - 2 chunks
  54. "return Promise.all([",
  55. Template.indent(
  56. chunkIds
  57. .map(
  58. id =>
  59. `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)})`
  60. )
  61. .join(",\n")
  62. ),
  63. "]).then(next);"
  64. ]
  65. )};`
  66. ]);
  67. }
  68. }
  69. module.exports = StartupChunkDependenciesRuntimeModule;