前端微前端:Module Federation+Vue/React 集成
·
前端微前端:Module Federation + Vue/React 集成
1. 核心概念
- 微前端:将大型应用拆分为独立开发、部署的子应用
- Module Federation:Webpack 5 原生支持的模块共享机制,关键配置项:
name: 应用标识符filename: 暴露的入口文件exposes: 导出的模块remotes: 引用的远程模块shared: 共享的依赖库
2. Vue 集成方案
宿主应用配置 (webpack.config.js):
const ModuleFederationPlugin = require("webpack").container.ModuleFederationPlugin;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: "host_app",
remotes: {
vue_remote: "vue_remote@http://remote-domain/vue-remote-entry.js"
},
shared: {
vue: { singleton: true, eager: true },
"vue-router": { singleton: true }
}
})
]
};
远程Vue应用配置:
new ModuleFederationPlugin({
name: "vue_remote",
filename: "vue-remote-entry.js",
exposes: {
"./VueComponent": "./src/components/ExposedComponent.vue"
},
shared: ["vue", "vue-router"]
});
3. React 集成方案
宿主应用配置:
new ModuleFederationPlugin({
name: "react_host",
remotes: {
react_remote: "react_remote@http://cdn-domain/react-remote-entry.js"
},
shared: ["react", "react-dom", "react-router-dom"]
});
远程React应用配置:
new ModuleFederationPlugin({
name: "react_remote",
filename: "react-remote-entry.js",
exposes: {
"./ReactWidget": "./src/Widget.jsx"
}
});
4. 跨框架组件使用
// Vue宿主中使用React远程组件
const RemoteReactComponent = React.lazy(
() => import("react_remote/ReactWidget")
);
function VueWrapper() {
return (
<Suspense fallback="Loading...">
<RemoteReactComponent />
</Suspense>
);
}
5. 关键优化策略
- 依赖共享:
shared: { react: { requiredVersion: "^18.0.0" }, "react-dom": { singleton: true } } - 动态加载:
const loadRemote = (url) => import(/* webpackIgnore: true */ url) - CSS隔离:
- 使用 Shadow DOM
- 添加命名空间前缀
- 通信机制:
- CustomEvents 全局事件总线
window.postMessage跨域通信
6. 部署架构
+-----------------+ +-----------------+
| Vue Host App |<----->| React Remote App |
| (main.domain) | | (app1.domain) |
+-----------------+ +-----------------+
↑ ↑
| |
+-----------------+ +-----------------+
| Module Federation| | Module Federation|
| Runtime | | Runtime |
+-----------------+ +-----------------+
7. 注意事项
- 版本控制:主/子应用的框架版本需兼容
- 性能监控:使用
webpack-bundle-analyzer分析模块大小 - 错误隔离:实现子应用沙箱机制
- 路由协调:统一使用前端路由库(如 Vue Router/React Router)
最佳实践:初始阶段建议采用单框架方案(全Vue或全React),待技术栈稳定后再引入跨框架集成。
更多推荐



所有评论(0)