如何配置 remote 和 host 应用实现跨应用组件共享?
解读
国内面试场景下,这道题考察的是“微前端”落地能力,尤其是 Webpack 5 Module Federation 在生产环境的真实配置与踩坑经验。面试官想确认:
- 你是否理解“把组件当服务”的共享思路;
- 能否独立搭出 remote 端(提供方)与 host 端(消费方)的完整链路;
- 是否具备灰度、版本回滚、性能监控等工程化意识。
只背诵“exposes/remotes 两个字段”远远不够,必须给出可复制的代码骨架、路径规范、CDN 策略、热更新兼容方案,以及国内网络(HTTPS 双证书、Nginx 跨域、公司私有 npm 源)下的常见坑。
知识点
- Module Federation 核心概念:remoteEntry.js、shared scope、fallback、singleton、strictVersion
- 构建阶段:publicPath 必须写成运行时变量,否则 CDN 迁移会 404
- 共享依赖:react、react-dom 必须 singleton,工具库建议统一 semver 范围,避免重复打包子模块
- 跨域:remoteEntry 请求需 CORS 头,国内云厂商 OSS+CDN 默认不开启,需要手动配置
- 热更新:dev 阶段用 webpack serve 的 liveReload 与 react-refresh-webpack-plugin,remote 更新后 host 需页面级刷新(HMR 作用域隔离)
- 灰度:在 remoteEntry 文件名里注入 git commit hash,通过 Nginx 按 cookie 灰度转发到不同目录
- 类型提示:remote 项目用 tsc 生成 .d.ts,host 项目通过 @types/xxx 或 Yarn workspace 协议链接,保证 IDE 不报错
- 监控:在 window 上埋点记录 remoteEntry 加载耗时,超过 1s 自动降级到本地备用组件
- 安全:remoteEntry.js 必须 SRI(Subresource Integrity)校验,防止 CDN 被篡改
- 低版本浏览器:需要额外加 System.js 垫片,或者 remote 端同时导出 umd 格式兜底
答案
(以下示例均以国内最常见的 monorepo + pnpm + GitLab CI 为背景,remote 与 host 同域不同路径,CDN 统一走 https://static.company.com)
- remote 端 webpack.config.js(提供 Button、Card 两个 React 组件)
const { ModuleFederationPlugin } = require('webpack').container;
const deps = require('./package.json').dependencies;
module.exports = {
mode: 'production',
output: {
// 关键:publicPath 写成运行时变量,方便 CDN 灰度切换
publicPath: 'auto',
uniqueName: 'mf_remote_goods',
// 带 hash 方便版本回滚
filename: '[name].[contenthash:8].js',
},
plugins: [
new ModuleFederationPlugin({
name: 'goods',
filename: 'remoteEntry.js',
exposes: {
'./Button': './src/components/Button',
'./Card': './src/components/Card',
},
shared: {
react: { singleton: true, requiredVersion: deps.react, strictVersion: true },
'react-dom': { singleton: true, requiredVersion: deps['react-dom'], strictVersion: true },
// 公司统一工具库
lodash: { singleton: true, requiredVersion: '^4.17.0' },
},
}),
],
};
CI 构建后把 dist 目录上传到 OSS,目录规则:
oss://static.company.com/mf/goods/<git-commit>/remoteEntry.js
Nginx 按 cookie 灰度转发:
map $cookie_mf_ver $mf_root {
default /mf/goods/release;
canary /mf/goods/<new-commit>;
}
location ~ ^/mf/goods/(.*) {
proxy_pass https://static.company.com/mf/goods/$1;
add_header Access-Control-Allow-Origin *;
}
- host 端 webpack.config.js(消费方)
const { ModuleFederationPlugin } = require('webpack').container;
const deps = require('./package.json').dependencies;
module.exports = {
mode: 'production',
plugins: [
new ModuleFederationPlugin({
name: 'main',
remotes: {
goods: 'goods@https://static.company.com/mf/goods/release/remoteEntry.js',
},
shared: {
react: { singleton: true, requiredVersion: deps.react, strictVersion: true },
'react-dom': { singleton: true, requiredVersion: deps['react-dom'], strictVersion: true },
lodash: { singleton: true, requiredVersion: '^4.17.0' },
},
}),
],
};
- host 端业务代码(React 17+)
import React, { Suspense, useEffect } from 'react';
// 动态加载,支持降级
const Button = React.lazy(() =>
import('goods/Button').catch(() => {
// 埋点
window.mfMonitor && window.mfMonitor('goods/Button', 'fail');
return import('../fallback/LocalButton');
})
);
export default function Page() {
useEffect(() => {
// 预加载 remoteEntry,提升秒开率
const link = document.createElement('link');
link.rel = 'prefetch';
link.href = 'https://static.company.com/mf/goods/release/remoteEntry.js';
document.head.appendChild(link);
}, []);
return (
<Suspense fallback={<div>加载中...</div>}>
<Button type="primary">远程按钮</Button>
</Suspense>
);
}
- 灰度与回滚
- 新功能上线时,先在 remote 端打新 commit,OSS 目录新增 /mf/goods/<new-commit>;
- 运维通过 Nginx 把内部员工 cookie(mf_ver=canary)转发到新目录;
- 监控无异常后,把 /mf/goods/release 软链指向新目录,完成全量;
- 一旦异常,回滚只需改软链,30 秒内生效。
- 本地开发联调
# remote 端
npm run serve // 端口 3001
# host 端 .env.local
MF_GOODS_URL=http://localhost:3001/remoteEntry.js
host 端 webpack 里 remotes 改成:
goods: `goods@${process.env.MF_GOODS_URL}`
即可实现本地热更新联调。
拓展思考
-
如果公司强制要求“离线包”方案(App 内嵌 H5),remoteEntry.js 需要打进本地包,如何动态切换本地/网络?
答:在 host 端先尝试 fetch 远程 remoteEntry,超时 500ms 则回退到本地 assets/mf/goods/remoteEntry.js,同时把版本号写入 localStorage,下次启动优先用本地。 -
如何做到“子应用独立部署,但主应用不重启”?
答:remoteEntry 文件名固定为 remoteEntry.js(不带 hash),内容里通过 webpack_require.l 动态加载带 hash 的 chunk;更新组件后只上传新 chunk,老用户仍在内存中运行旧版本,新用户拉新 chunk,实现“版本漂移”。 -
如果 remote 用 Vue 3,host 用 React 18,是否还能共享?
答:可以共享工具库(lodash、dayjs),但 UI 框架无法共享,需各自打包。此时应把“业务组件”拆成框架无关的 Web Components,remote 端用 defineCustomElements 注册,host 端直接当普通 DOM 节点使用,实现真正的技术栈无关共享。 -
国内小程序容器内无法动态请求远程 JS,如何变通?
答:remote 端在 CI 阶段把组件编译成小程序自定义组件,上传到公司私有的“小程序组件市场”,host 端通过 npm 安装后静态打包,放弃运行时共享,退而求“编译时共享”,仍能保持版本统一。