-
Notifications
You must be signed in to change notification settings - Fork 266
/
Copy pathimport-shared.js
40 lines (40 loc) · 1.4 KB
/
import-shared.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
export const importShared = function () {
if (!globalThis.importShared) {
const moduleCache = Object.create(null)
const getSharedFromRuntime = async (name, shareScope) => {
let module = null
if (globalThis?.__federation_shared__?.[shareScope]?.[name]) {
const versionObj = globalThis.__federation_shared__[shareScope][name]
const versionValue = Object.values(versionObj)[0]
module = await (await versionValue.get())()
}
if (module) {
return flattenModule(module, name)
}
}
const flattenModule = (module, name) => {
// use a shared module which export default a function will getting error 'TypeError: xxx is not a function'
if (typeof module.default === 'function') {
Object.keys(module).forEach((key) => {
if (key !== 'default') {
module.default[key] = module[key]
}
})
moduleCache[name] = module.default
return module.default
}
if (module.default) module = Object.assign({}, module.default, module)
moduleCache[name] = module
return module
}
globalThis.importShared = async (name, shareScope = 'default') => {
try {
return moduleCache[name]
? new Promise((r) => r(moduleCache[name]))
: (await getSharedFromRuntime(name, shareScope)) || null
} catch (ex) {
console.log(ex)
}
}
}
}