微前端架构指南

方案对比

方案集成方式隔离性复杂度最适合
Module Federation (Webpack 5)构建时共享运行时React/Vue 应用,紧密集成
single-spa运行时应用级隔离混合框架,遗留系统迁移
Web Components运行时Shadow DOM 隔离低-中框架无关的小部件
iframe运行时完全隔离第三方集成
服务端组合服务端完全隔离SSR 页面、Edge Side Includes

Module Federation (Webpack 5)

// 宿主应用 — webpack.config.js new ModuleFederationPlugin({ name: 'host', remotes: { checkout: 'checkout@https://checkout.example.com/remoteEntry.js', catalog: 'catalog@https://catalog.example.com/remoteEntry.js', }, shared: { react: { singleton: true, requiredVersion: '^18.0.0' }, 'react-dom': { singleton: true, requiredVersion: '^18.0.0' }, }, }) // 远程应用 — webpack.config.js new ModuleFederationPlugin({ name: 'checkout', filename: 'remoteEntry.js', exposes: { './CheckoutFlow': './src/CheckoutFlow', './CartButton': './src/CartButton', }, shared: { react: { singleton: true } }, }) // 在宿主中使用 const CheckoutFlow = React.lazy(() => import('checkout/CheckoutFlow'));

通信模式

模式使用场景示例
自定义事件松耦合、同页面事件window.dispatchEvent(new CustomEvent('cart:add', {detail: item}))
共享状态 (Redux)跨 MFE 全局状态宿主中单一 Store,远程应用消费
URL / 路由参数导航数据传递React Router 或原生 history API
Props / 回调父子 MFE 数据传递Module Federation 暴露的组件 props
BroadcastChannel跨标签页通信new BroadcastChannel('app')