Webpack 5 模块联邦(Module Federation)
Webpack 5 模块联邦(Module Federation)#
核心能力:运行时动态加载远程模块,实现微前端独立部署。
架构角色#
| 角色 | 作用 | 配置 |
|---|---|---|
| Host(宿主) | 消费远程模块 | remotes |
| Remote(远程) | 暴露自身模块供他人使用 | exposes |
| Shared(共享) | 依赖共享,避免重复加载 | shared |
代码示例#
Remote 暴露模块(独立部署)#
// webpack.config.js
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'remoteApp', // 远程应用名称
filename: 'remoteEntry.js', // 入口文件
exposes: {
'./Button': './src/Button', // 暴露的模块
'./utils': './src/utils',
},
shared: ['react', 'react-dom'], // 共享依赖
}),
],
};javascriptHost 消费远程模块#
// webpack.config.js
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'hostApp',
remotes: {
// 运行时动态加载
remoteApp: 'remoteApp@http://localhost:3001/remoteEntry.js',
},
shared: ['react', 'react-dom'],
}),
],
};javascript// 组件中使用远程模块
import React, { lazy, Suspense } from 'react';
// 动态导入远程组件
const RemoteButton = lazy(() => import('remoteApp/Button'));
function App() {
return (
<Suspense fallback="Loading...">
<RemoteButton /> {/* 来自另一个部署! */}
</Suspense>
);
}jsx共享依赖机制#
场景:Host 和 Remote 都依赖 React
无 shared:各自打包 React,页面加载 2 份(体积大)
有 shared:运行时协商版本,只加载 1 份(自动降级/升级)plaintextshared: {
react: {
singleton: true, // 强制单例
requiredVersion: '^18.0.0',
version: '18.2.0', // 自身版本
},
}javascript