Webpack 5 的 Module Federation 如何实现远程模块共享?

解读

国内一线/二线大厂在落地微前端、跨仓库组件复用、灰度发布时,几乎必问“Module Federation(MF)到底怎么把远端包挂到本地运行时”。面试官想确认三点:

  1. 你是否真的搭过 MF,还是只看过概念;
  2. 对“运行时动态加载 + 依赖单例”机制是否理解到位;
  3. 能否讲清楚生产环境如何落地(域名、版本、灰度、回滚、性能、安全)。
    回答时先给“一句话原理”,再拆“配置-构建-运行”三步,最后补“踩坑+治理”,就能拿到高分。

知识点

  1. Container: 暴露方(remote)把子模块打成一个可运行时挂载的容器,文件名默认 remoteEntry.js。
  2. Host: 消费方把 remote 当 externals 用,但不在编译期打包,而在运行时通过 JSONP 拉取。
  3. shared: 双方把 react、react-dom、lodash 等统一提升到“共享作用域”,保证单例,避免重复加载。
  4. 运行时流程:
    __webpack_init_sharing__ → 创建共享作用域 → container.init(__webpack_share_scopes__.default) → container.get('./Button') → 返回 factory → factory() 得到模块。
  5. 国内特有细节:
    • 跨域必须配 Access-Control-Allow-Origin: * 或白名单;
    • 灰度发布靠 nginx 按 cookie 分流到不同 remoteEntry 目录;
    • 为了 CDN 缓存,remoteEntry 带 chunkhash,但共享库用固定文件名 + 长缓存。

答案

一句话原理:MF 把“子应用”打成“运行时容器”,主应用在浏览器里通过 JSONP 动态拉取该容器,再通过共享作用域把依赖对齐,实现“代码在远端、运行在同一上下文”。

落地三步走:

  1. 暴露方(remote)webpack.config.js
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');

module.exports = {
  output: {
    publicPath: 'https://static.a.com/mf/', // 国内 CDN 域名
    uniqueName: 'profile',                // 防止全局变量冲突
  },
  plugins: [
    new ModuleFederationPlugin({
      name: 'profile',
      filename: 'remoteEntry.[contenthash:8].js',
      exposes: {
        './Button': './src/components/Button',
        './routes': './src/routes',
      },
      shared: {
        react: { singleton: true, requiredVersion: '^18.0.0', strictVersion: true },
        'react-dom': { singleton: true, requiredVersion: '^18.0.0' },
      },
    }),
  ],
};

构建后上传 CDN,得到 https://static.a.com/mf/remoteEntry.abc123.js。

  1. 消费方(host)webpack.config.js
new ModuleFederationPlugin({
  name: 'main',
  remotes: {
    profile: 'profile@https://static.a.com/mf/remoteEntry.abc123.js',
  },
  shared: {
    react: { singleton: true, requiredVersion: '^18.0.0' },
    'react-dom': { singleton: true },
  },
});
  1. 业务代码里使用
import React, { Suspense, lazy } from 'react';
const ProfileButton = lazy(() => import('profile/Button'));

function App() {
  return (
    <Suspense fallback={<div>loading...</div>}>
      <ProfileButton />
    </Suspense>
  );
}

运行时:

  • 浏览器先加载主应用;
  • 遇到 import('profile/Button'),webpack 内部创建 script 标签去拉 remoteEntry.abc123.js;
  • remoteEntry 把自己注册到全局 window.profile;
  • host 调用 window.profile.get('./Button') 拿到 factory,执行后返回真正的 React 组件;
  • 如果 shared 里规定 react 为 singleton,remoteEntry 里的 react 不会执行,直接复用主应用的 react,保证 Hooks 上下文一致。

生产治理:

  • 灰度:nginx 根据 cookie 把 remoteEntry.xxx.js 指向不同目录,回滚只需切流量;
  • 版本锁:host 的 remotes 配置通过配置中心下发,上线前对比版本号,防止 breaking change;
  • 监控:在 container.get() 外层包一层 try/catch,把失败信息打到 sentry,同时自动降级成本地组件;
  • 安全:remoteEntry 域名加入 CSP script-src 白名单,避免 XSS 注入。

拓展思考

  1. 模块联邦 vs qiankun:MF 是“构建时拆分 + 运行时共享”,适合“同技术栈 + 共享库”场景;qiankun 是“运行时隔离 + 快照沙箱”,适合“异构框架 + 老系统”。国内很多团队把二者结合:qiankun 做子应用隔离,MF 做公共组件共享。
  2. 服务端渲染:MF 默认只支持浏览器,SSR 需要自定义 Node 插件,在服务端也维护一份 __webpack_share_scopes__,否则会出现“服务端多实例、客户端单实例”导致的 hydrate 失败。
  3. 依赖升级策略:shared 的 strictVersion:true 会在版本不匹配时直接抛错,适合强制对齐;若允许向后兼容,可关掉 strictVersion,通过配置中心动态下发“版本区间”,实现渐进式升级。