演示使用 Module Federation 2025 让 Boot 3.2 动态加载 React 微前端
解读
国内大厂目前把“后端也要能托管并动态下发微前端”当成云原生架构的标配。面试官想确认:
- 你是否真的在 Boot3 生产环境落地过 MF,而不是只会跑 demo;
- 你对“构建产物如何被 Boot 安全、版本化、灰度下发”有没有闭环方案;
- 能否把 MF 的 runtime 与 Boot 的 actuator、配置中心、网关 打通,做到“后端驱动前端灰度”。
一句话:他要的是“Boot 作为微前端配置中心 + 静态宿主”的完整套路,而不是单纯在 React 里配个 federation。
知识点
- Module Federation 2025(Webpack 5.93+)新特性:
–runtimeChunk: 'mf-runtime'支持把远程容器拆成独立 chunk,可被 Boot 动态注入;
–library: { type: 'global', name: 'app_[name]' }与 Java 的 Nashorn/GraalJS 全局变量打通;
–sharePolicy: 'version-first'解决多团队共享依赖版本漂移。 - Boot 3.2 静态资源策略:
–spring.web.resources.chain.strategy.content.versioned开启内容哈希版本链;
–ResourceResolver自定义MfVersionResolver,把 MF 的remoteEntry.js纳入版本管理;
–WebMvcConfigurer添加addResourceHandlers映射/mf/**到classpath:/static/mf/并加Cache-Control: no-cache, must-revalidate,防止浏览器缓存导致灰度失效。 - 动态下发与灰度:
– 配置中心(Nacos 2.3)维护mf.manifest.json(远程模块名↔文件哈希↔灰度标签);
– Boot 启动时把清单写入MfManifestService,通过/actuator/mf-manifest端点暴露;
– 前端 shell 通过fetch('/actuator/mf-manifest')拉取当前环境应加载的 remoteEntry 地址,实现后端驱动的 A/B。 - 安全与隔离:
– 使用 Subresource Integrity:remoteEntry.js的哈希在清单里带integrity="sha256-xxx",由 Boot 统一计算;
– 通过Content-Security-Policy: script-src 'self' 'sha256-xxx'阻断非法注入;
– 远程模块沙箱:MF 2025 的sandbox: 'strict'模式 + 前端 Qiankun 快照沙箱双保险。 - 构建流水线:
– GitLab CI 先跑npm run build:micro,产物上传到 私有 OSS(阿里云 OSS + CDN);
– Boot 打镜像时只拉取manifest.json与remoteEntry.[hash].js到src/main/resources/static/mf/;
– 灰度发布通过 Argo Rollout 修改 ConfigMap 中的mf.manifest.json版本号,Pod 无损热加载。
答案
下面给出一份可直接落地的“10 分钟能让面试官看懂的代码 + 口述”:
- 后端:Boot 3.2 暴露清单接口
@RestController
@RequiredArgsConstructor
@RequestMapping("/actuator")
public class MfManifestEndpoint {
private final MfManifestService service;
@GetMapping(value = "/mf-manifest", produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String, Object> manifest() {
return service.getManifest(); // 从 Nacos 实时拉取
}
}
配置类把静态目录加缓存策略:
@Configuration
public class MfResourceConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/mf/**")
.addResourceLocations("classpath:/static/mf/")
.setCacheControl(CacheControl.noCache().mustRevalidate())
.resourceChain(true)
.addResolver(new VersionResourceResolver()
.addContentVersionStrategy("/**"));
}
}
- 前端:React shell 使用 MF 2025 语法
// webpack.config.js
const ModuleFederationPlugin = require('@module-federation/enhanced/webpack');
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'shell',
remotes: {
// 运行时才决定地址
microA: 'promise @mf-get microA'
},
shared: {
react: { singleton: true, requiredVersion: '^18.2.0', sharePolicy: 'version-first' }
}
})
]
};
在 index.js 里动态注入:
window.__mf_get = async (name) => {
const { url, integrity } = await fetch('/actuator/mf-manifest')
.then(r => r.json())
.then(m => m[name]);
const script = document.createElement('script');
script.src = url;
script.integrity = integrity;
script.crossOrigin = 'anonymous';
document.head.appendChild(script);
return new Promise(res => script.onload = () => res(window[`app_${name}`]));
};
- 灰度演示(口述即可)
“我们在 Nacos 里给mf.manifest.json加了一个tag=gray的键,只有带gray=1的 Cookie 请求才会返回新的remoteEntry.abc123.js,否则返回旧的remoteEntry.def456.js。通过 Boot 的HandlerInterceptor读取 Cookie 并动态切换MfManifestService里的版本,实现了零重启灰度。”
拓展思考
- MF 与 Server-Side Rendering 同构:
Boot 3.2 可以内嵌 GraalVM 跑react-dom/server,把远程组件在 Java 里直出 HTML,解决国内 SEO 强需求。思路是把remoteEntry.js用graaljs执行,取出export.serverRender方法,缓存到 Caffeine,QPS 可做到 1w+。 - 联邦模块热插拔:
利用 MF 2025 的unloadModule()API,结合 Boot 的ShutdownHook,可在运行时卸载有内存泄漏的远程包,实现线上不停机替换前端页面。 - 安全左移:
在 Maven 编译期用 frontend-maven-plugin 把remoteEntry.js的 AST 做 IAST 扫描,一旦识别出eval、document.write直接阻断构建,防止第三方微前端投毒。
把以上三点在面试尾声抛出来,基本能锁定架构师级别的评分。