解决 Webpack 模块联邦 报错 ScriptExternalLoadError remoteEntry.js 加载失败修复
排查 微前端使用 Webpack 5 ModuleFederationPlugin 加载远端微应用时报 ScriptExternalLoadError: Loading script failed for remoteEntry.js,分析 跨域 CORS、publicPath 动态补全与资源 Hash 缓存失效。
问题现象
基座主应用(Host)在动态路由切换尝试加载子应用(Remote)组件时,控制台抛出远程脚本加载中断错误:
ScriptExternalLoadError: Loading script failed.
(missing: http://localhost:3001/remoteEntry.js)
while loading "./Header" from webpack/container/reference/remote_app
触发根因
- 子应用构建配置中缺少
publicPath: 'auto',导致 Webpack 在主应用域名上下文中向错误的相对路径发起二次 Chunk 请求; - 部署子应用静态资源的 CDN 或 Nginx 服务器未放行跨域标头(
Access-Control-Allow-Origin: *); - 子应用发版后静态文件名 Hash 变更,主应用依然持有着旧版
remoteEntry.js的内存引用。
解决步骤
在子应用 webpack.config.js 中配置 publicPath 为 auto
保证资源绝对路径自适应:
module.exports = {
output: {
publicPath: 'auto',
clean: true,
},
plugins: [
new ModuleFederationPlugin({
name: 'remote_app',
filename: 'remoteEntry.js',
exposes: { './Header': './src/Header' },
shared: { react: { singleton: true }, 'react-dom': { singleton: true } },
}),
],
};
确保子应用 Nginx 服务器配置规范的 CORS 头与强缓存禁用
在 remoteEntry.js 所在虚拟主机中配置:
location ~* remoteEntry\.js$ {
add_header Access-Control-Allow-Origin *;
add_header Cache-Control "no-cache, no-store, must-revalidate";
}
在主应用中使用动态加载容器配合加载失败重试边界
增加 Error Boundary 优雅降级。
验证确认
重新刷新基座主应用:
remoteEntry.js 毫秒级通过跨域网络拉取并在主应用中无缝渲染,微前端模块动态联邦正常流转。


