StartupChunkDependenciesRuntimeModule.js 2.2 KB

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