模块联邦中远程组件加载失败怎么办?
我在用 Webpack 5 的模块联邦搞微前端,本地调试时主应用能正常加载远程组件,但部署到测试环境后就报错了,控制台提示找不到 remoteEntry.js。
我检查了 remote 的 publicPath,也配成了绝对路径,比如 https://remote.example.com/,但还是不行。主应用的配置大概是这样:
new ModuleFederationPlugin({
name: 'host',
remotes: {
remoteApp: 'remoteApp@https://remote.example.com/remoteEntry.js'
},
// ...
})
远程应用那边也确认 remoteEntry.js 能直接访问到,但主应用一加载就报错:Uncaught (in promise) Error: Module “./Button” does not exist in container. 这到底是哪出问题了?
exposes配置没配对。你 remoteEntry.js 能访问到,说明 remote 应用的入口配置没问题。报错 "Module ./Button does not exist in container" 的意思是 remoteEntry 加载成功了,但是它里面没找到你暴露的 Button 模块。
检查一下 remote 应用的配置,大概应该是这样:
重点看两点:
第一,
exposes的 key 是./Button,那么主应用那边必须用完全一样的 key 来引用,比如const Button = React.lazy(() => import('remoteApp/Button')),拼错了就会报这个错。第二,确认 remote 应用的
publicPath配的是测试环境的绝对路径。本地开发时可能是./,但部署后必须改成https://remote.example.com/,否则它加载内部 chunk 时会拼错路径。还有一个小坑:如果 remote 应用用了
webpack runtime相关的配置或者有多个 entry,可能需要检查一下filename是否一致。你先看一下 remote 端有没有正确 exposes,路径对不对。