React Vite Module Federation报错:无法获取动态导入模块,宿主应用无法访问remoteEntry.js
React Vite Module Federation 报错:TypeError: Failed to fetch dynamically imported module
宿主应用无法访问远程应用的remoteEntry.js文件,抛出TypeError: Failed to fetch dynamically imported module错误。
远程应用配置
// https://vitejs.dev/config/ export default defineConfig({ plugins: [ react(), federation({ name: 'remote_app', filename: 'remoteEntry.js', exposes: { './App': './src/App', }, shared: [ ...... 'react', 'react-dom', 'react-query', 'react-router-dom', ], }), ], build: { modulePreload: false, target: 'esnext', minify: false, cssCodeSplit: false, }, });
宿主应用配置
// https://vitejs.dev/config/ export default defineConfig({ plugins: [ react(), federation({ name: 'app', remotes: { remoteApp: 'http://localhost:5001/assets/remoteEntry.js', }, shared: ['react', 'react-dom'], }), ], build: { modulePreload: false, target: 'esnext', minify: false, cssCodeSplit: false, }, })
执行命令
- 两个应用均执行:
npm run build - 两个应用均执行:
npm run dev
排查与解决步骤
验证远程服务可用性
直接在浏览器访问http://localhost:5001/assets/remoteEntry.js,确认能正常加载文件。如果返回404,检查远程应用的启动端口是否为5001,或资源路径是否配置错误。核对资源输出路径
查看远程应用build后的dist文件夹结构,确认remoteEntry.js的实际位置。如果文件直接在dist根目录,宿主配置的路径应改为http://localhost:5001/remoteEntry.js。解决跨域问题
若宿主与远程应用端口不同,在远程应用的Vite配置中添加CORS允许:server: { cors: true, port: 5001 }调整开发模式流程
Vite Module Federation在开发模式下无需提前执行npm run build,直接启动npm run dev即可。删除两个应用的dist文件夹后重新启动开发服务测试。统一共享依赖版本
确保宿主与远程应用的react、react-dom等共享依赖版本完全一致,版本差异可能导致动态导入失败。
内容的提问来源于stack exchange,提问作者Joshua Duxbury
相关产品推荐
相关产品推荐

