AsyncModuleGeneratorRuntimeModule.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. const RuntimeGlobals = require("../RuntimeGlobals");
  6. const Template = require("../Template");
  7. const HelperRuntimeModule = require("./HelperRuntimeModule");
  8. /** @import Compilation from "../Compilation" */
  9. class AsyncModuleGeneratorRuntimeModule extends HelperRuntimeModule {
  10. constructor() {
  11. super("async module generator");
  12. }
  13. /**
  14. * Returns true, if the runtime module should get it's own scope.
  15. * When false, `generate()` must emit complete statements ending with `;`
  16. * so a following runtime IIFE is not parsed as a call (ASI).
  17. * @returns {boolean} true, if the runtime module should get it's own scope
  18. */
  19. shouldIsolate() {
  20. return false;
  21. }
  22. /**
  23. * Generates runtime code for this runtime module.
  24. * @returns {string | null} runtime code
  25. */
  26. generate() {
  27. const compilation = /** @type {Compilation} */ (this.compilation);
  28. const { runtimeTemplate } = compilation;
  29. const fn = RuntimeGlobals.asyncModuleGenerator;
  30. const cst = runtimeTemplate.renderConst();
  31. // Wrap a generator-based async module body so it drives like an `async`
  32. // function: run the generator and resolve each `yield`ed dependency
  33. // promise, without emitting `async`/`await`.
  34. return Template.asString([
  35. `${fn} = ${runtimeTemplate.returningFunction(
  36. runtimeTemplate.basicFunction(
  37. "__webpack_handle_async_dependencies__, __webpack_async_result__",
  38. [
  39. `${cst} gen = body(__webpack_handle_async_dependencies__, __webpack_async_result__);`,
  40. `${cst} step = ${runtimeTemplate.basicFunction("key, arg", [
  41. `${cst} info = gen[key](arg);`,
  42. "if (info.done) return;",
  43. `Promise.resolve(info.value).then(${runtimeTemplate.expressionFunction(
  44. 'step("next", value)',
  45. "value"
  46. )}, ${runtimeTemplate.expressionFunction(
  47. 'step("throw", err)',
  48. "err"
  49. )});`
  50. ])};`,
  51. 'step("next");'
  52. ]
  53. ),
  54. "body"
  55. )};`
  56. ]);
  57. }
  58. }
  59. module.exports = AsyncModuleGeneratorRuntimeModule;