我已经实现了一段时间,也在 MFE 之间使用 redux 进行应用间通信。
商店是在子应用中单独构建的。
该商店将由主应用导入并在主应用的全球事件分发器中注册。
class GlobalEventDistributor {
constructor() {
this.stores = [];
}
registerStore(store) {
this.stores.push(store);
}
dispatch(event) {
this.stores.forEach((s) => s.dispatch(event));
}
}
这个 GlobalEventDistributor 和 store 将在注册应用程序时作为自定义 prop 传递。
let storeModule = {},
customProps = {
globalEventDistributor: globalEventDistributor,
...additionalProps,
};
try {
storeModule = storeURL
? await SystemJS.import(storeURL)
: { storeInstance: null };
} catch (e) {
console.error(`Could not load store of app ${name}.`, e);
}
if (storeModule.storeInstance && globalEventDistributor) {
// add a reference of the store to the customProps
customProps.store = storeModule.storeInstance;
// register the store with the globalEventDistributor
globalEventDistributor.registerStore(storeModule.storeInstance);
}
// register the app with singleSPA and pass a reference to the store of the app as well as a reference to the globalEventDistributor
singleSpa.registerApplication(
name,
() => SystemJS.import(appURL),
hashPrefix(hash, wild),
customProps
);
作为customer props store 传递后,GlobalEventDispatcher 将在传递给子应用的singleSpaReact 的rootComponent 中可用。从 rootComponent 它将作为道具传递给 Provider
我在实现它时参考了下面的 repo。
https://github.com/me-12/single-spa-portal-example
注意:目前我们正在迁移到 Module Federation 而不是使用 singleSPA,您也可以尝试。