模块联邦中远程组件加载失败怎么办?

耘博酱~ 阅读 2

我在用 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. 这到底是哪出问题了?

我来解答 赞 1 收藏
二维码
手机扫码查看
1 条解答
极客国曼
这个问题很典型,十有八九是 remote 端的 exposes 配置没配对。

你 remoteEntry.js 能访问到,说明 remote 应用的入口配置没问题。报错 "Module ./Button does not exist in container" 的意思是 remoteEntry 加载成功了,但是它里面没找到你暴露的 Button 模块。

检查一下 remote 应用的配置,大概应该是这样:

new ModuleFederationPlugin({
name: 'remoteApp',
filename: 'remoteEntry.js',
exposes: {
'./Button': './src/components/Button' // 这个路径要对到你实际的组件文件
},
shared: { react: { singleton: true }, 'react-dom': { singleton: true } }
})


重点看两点:

第一,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,路径对不对。
点赞
2026-03-10 20:02