AwaitDependenciesInitFragment.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const InitFragment = require("../InitFragment");
  7. const RuntimeGlobals = require("../RuntimeGlobals");
  8. const Template = require("../Template");
  9. /** @typedef {import("webpack-sources").Source} Source */
  10. /** @typedef {import("../Generator").GenerateContext} GenerateContext */
  11. /**
  12. * @typedef {GenerateContext} Context
  13. */
  14. class AwaitDependenciesInitFragment extends InitFragment {
  15. /**
  16. * @param {Set<string>} promises the promises that should be awaited
  17. */
  18. constructor(promises) {
  19. super(
  20. undefined,
  21. InitFragment.STAGE_ASYNC_DEPENDENCIES,
  22. 0,
  23. "await-dependencies"
  24. );
  25. this.promises = promises;
  26. }
  27. merge(other) {
  28. const promises = new Set(other.promises);
  29. for (const p of this.promises) {
  30. promises.add(p);
  31. }
  32. return new AwaitDependenciesInitFragment(promises);
  33. }
  34. /**
  35. * @param {Context} context context
  36. * @returns {string|Source} the source code that will be included as initialization code
  37. */
  38. getContent({ runtimeRequirements }) {
  39. runtimeRequirements.add(RuntimeGlobals.module);
  40. const promises = this.promises;
  41. if (promises.size === 0) {
  42. return "";
  43. }
  44. if (promises.size === 1) {
  45. for (const p of promises) {
  46. return Template.asString([
  47. `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${p}]);`,
  48. `${p} = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];`,
  49. ""
  50. ]);
  51. }
  52. }
  53. const sepPromises = Array.from(promises).join(", ");
  54. // TODO check if destructuring is supported
  55. return Template.asString([
  56. `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${sepPromises}]);`,
  57. `([${sepPromises}] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);`,
  58. ""
  59. ]);
  60. }
  61. }
  62. module.exports = AwaitDependenciesInitFragment;