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