-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple-ioc.js
55 lines (49 loc) · 1.88 KB
/
simple-ioc.js
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
let dependencies = [];
let loadedDependencies = {};
export function addDependencies(deps = []) {
dependencies = [...deps, ...dependencies];
}
export async function inject(deps = {}, customResolver, useCdn = typeof window !== "undefined") {
if (customResolver === true) {
useCdn = true;
customResolver = undefined;
}
if (useCdn === true) return injectCDN(deps, customResolver);
for (const {specifier, resolver, exports} of dependencies) {
let library;
if (deps[specifier]) {
library = deps[specifier];
// Override dep resolution
loadedDependencies[specifier] = library;
if (exports) {
if (typeof exports === "string") {
loadedDependencies[exports] = library;
} else {
for (const exportAs of Object.values(exports)) {
loadedDependencies[exportAs] = library;
}
}
} else {
loadedDependencies[specifier] = library;
}
} else if (!loadedDependencies[specifier]) {
// Resolve dep.
library = await (customResolver || resolver)(specifier);
if (exports) {
if (typeof exports === "string") {
loadedDependencies[exports] = library;
} else {
for (const [libExport, exportAs] of Object.entries(exports)) {
loadedDependencies[exportAs] = library[libExport];
}
}
} else {
loadedDependencies[specifier] = library;
}
}
}
return loadedDependencies;
}
export async function injectCDN(deps = {}, cdnFormatter = specifier => `https://esm.run/${specifier}`) {
return inject(deps, specifier => import(cdnFormatter(specifier)), false);
}