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. 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 => {
  29. return chunk.id;
  30. });
  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. ? chunkIds
  39. .map(
  40. id => `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)});`
  41. )
  42. .concat("return next();")
  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;