如何配置 webpack 5 ModuleFederationPlugin 暴露组件
解读
在国内一线/二线大厂的微前端面试中,Module Federation(MF)已经从“加分项”变成“必答题”。
面试官真正想确认的是:
- 你是否理解“把组件当作远程模块”这一颠覆性思路;
- 能否独立写出生产级配置(含路径、共享依赖、版本兜底、TS 声明、CI 集成);
- 是否踩过“本地开发热更新失效”“样式冲突”“重复 React 实例”这些真实坑。
回答时切忌只贴一段“name/remotes/exposes”三件套,而要体现“能落地、能排障、能优化”。
知识点
- Module Federation 核心概念:Host vs Remote、shared scope、fallback、singleton、strictVersion
- exposes 语法:模块路径必须以“./”开头,key 即远程引用路径
- shared 配置:eager、requiredVersion、import、packageName 的用法
- 远程类型声明:@module-federation/typescript、react-app-rewired-mf、或者手写 global.d.ts
- 运行时变量注入:webpack_share_scopes、webpack_init_sharing
- 与 React 结合:React.lazy + React.Suspense 动态加载远程组件,ErrorBoundary 兜底
- 国内常见部署:Nginx 静态目录、OSS + CDN、qiankun 作为加载器、SSR 场景下用 Node 端 webpack 5
- 典型坑:
– 热更新端口冲突 → 配置 devServer.client.port / firewall
– 样式丢失 → 远程组件使用 mini-css-extract-plugin,host 必须同样配置
– 重复 React → shared 里强制 singleton、requiredVersion 用 “^18.0.0” 并开启 strictVersion
– 路径 404 → publicPath 必须写成 “https://cdn.xxx.com/remoteEntry/” 且带尾部斜杠
– 灰度发布 → remoteEntry.js 文件名带 [contenthash],Nginx 设置 Cache-Control: no-cache
答案
以下示例基于 monorepo 子包 “react-components”,目标是把 暴露给所有消费方,同时保证 React、ReactDOM 不重复加载。
目录结构
packages/components/src/Button/index.tsx
packages/components/webpack.config.js
- 暴露方(Remote)配置
// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');
const deps = require('./package.json').dependencies;
module.exports = (env, argv) => ({
mode: argv.mode || 'development',
entry: './src/index.ts',
output: {
// 国内 CDN 真实路径,尾部斜杠必须
publicPath: argv.mode === 'production'
? 'https://cdn.mycompany.com/react-components/'
: 'http://localhost:3001/',
clean: true,
},
resolve: { extensions: ['.tsx', '.ts', '.jsx', '.js'] },
module: {
rules: [
{ test: /\.tsx?$/, use: 'babel-loader', exclude: /node_modules/ },
{ test: /\.css$/, use: ['style-loader', 'css-loader'] },
],
},
plugins: [
new ModuleFederationPlugin({
name: 'react_components',
filename: 'remoteEntry.js', // 消费方引用地址
exposes: {
'./Button': './src/Button/index.tsx',
'./Modal': './src/Modal/index.tsx',
},
shared: {
react: {
singleton: true,
requiredVersion: deps.react,
strictVersion: true, // 版本不一致直接报错,防止软隐错
},
'react-dom': {
singleton: true,
requiredVersion: deps['react-dom'],
strictVersion: true,
},
},
}),
new HtmlWebpackPlugin({ template: './public/index.html' }),
],
devServer: {
port: 3001,
headers: {
'Access-Control-Allow-Origin': '*', // 本地跨域
},
},
});
- 消费方(Host)配置
// webpack.config.js(片段)
new ModuleFederationPlugin({
name: 'main_app',
remotes: {
react_components: 'react_components@https://cdn.mycompany.com/react-components/remoteEntry.js',
},
shared: {
react: { singleton: true, requiredVersion: '^18.0.0', strictVersion: true },
'react-dom': { singleton: true, requiredVersion: '^18.0.0', strictVersion: true },
},
});
- 消费方组件内使用
import React, { lazy, Suspense } from 'react';
const RemoteButton = lazy(() => import('react_components/Button'));
export default function Page() {
return (
<Suspense fallback={<div>加载中...</div>}>
<RemoteButton size="large" onClick={() => alert('远程按钮')}>
保存
</RemoteButton>
</Suspense>
);
}
- TypeScript 声明(手动写法,国内项目常用)
// src/global.d.ts
declare module 'react_components/Button' {
const Button: React.FC<any>;
export default Button;
}
- 生产环境验证清单
- CDN 文件可访问:curl https://cdn.mycompany.com/react-components/remoteEntry.js
- shared 版本一致:主机与远程的 package.json react 版本号前缀相同
- 灰度发布:remoteEntry.js 设置 Cache-Control: no-cache,其余资源设置 1 年缓存
- 监控:Sentry 上报 “Script error” 比例,超过 1% 立即回滚
- 构建提速:使用 webpack 5 的 “cache: { type: 'filesystem' }”,GitLab CI 缓存 .webpack-cache
拓展思考
-
如果远程组件使用 antd v5,而主机使用 antd v4,如何做到样式隔离?
思路:antd v5 默认 CSS-in-JS,可关闭 hash;远程组件打包时把 antd 标记为 singleton:false,主机通过 theme 变量覆盖;或者使用 @ant-design/cssinjs 的 StyleProvider 指定 container,避免全局污染。 -
在 SSR 场景(Next.js 12+)如何动态注入 remoteEntry?
思路:Next.js 禁用默认 webpack 5 外部化,重写 next.config.js 的 webpack 配置,在 Node 端使用 @module-federation/node 插件;页面级 getServerSideProps 里通过 streaming 注入 remote 组件,注意 React hydrate checksum 一致。 -
国内低代码平台把 MF 当“插件市场”,如何防止恶意远程脚本?
思路:remoteEntry.js 走公司统一网关,加签名校验(JWT + 时间戳);在运行时通过 import.meta.url 做 CSP 白名单;沙箱层可结合 qiankun 的 proxySandbox,限制 remote 组件访问 window、document。 -
微前端“去中心化管理”争议:MF 没有主注册中心,如何发现服务?
国内解法:- 把 remoteEntry 路径写入 Nacos / Apollo,消费方启动时拉取;
- 使用 Service Worker 做离线缓存与灰度开关;
- 结合 Dapr Sidecar 做服务健康检查,remoteEntry 404 自动降级到本地备用组件。
-
未来趋势:Rspack、Turbopack 都已支持 MF 协议,面试时可主动提及“如果迁移到 Rust 工具链,只需改构建器,remote 与 host 的协议层保持不变”,体现技术前瞻性。