Next.js模块联邦构建微前端报错:无法解析components/MovieCard
微前端构建问题:Next.js Module Federation 组件引用失败
我尝试使用@module-federation/nextjs-mf npm包,通过Next CLI在父文件夹内创建home和reactcomponents两个独立Next.js项目构建微前端,将reactcomponents中的组件共享给home项目,但运行home项目时出现组件找不到的错误。
reactcomponents项目的next.config.js配置
const NextFederationPlugin = require('@module-federation/nextjs-mf'); module.exports = { webpack(config, options) { if (!options.isServer) { config.plugins.push( new NextFederationPlugin({ name: 'components', filename: 'static/chunks/remoteEntry.js', exposes: { "./Button": "./components/Button.jsx", "./MovieCard": "./components/MovieCard.jsx" }, }), ); } return config; }, };
home项目的next.config.js配置
const NextFederationPlugin = require('@module-federation/nextjs-mf'); module.exports = { webpack(config, options) { if (!options.isServer) { config.plugins.push( new NextFederationPlugin({ name: 'home', filename: 'static/chunks/remoteEntry.js', remotes: { components: "components@http//localhost:3001/.next/static/chunks/remoteEntry.js" } }), ); } return config; }, };
报错信息
浏览器报错
Module not found: Can't resolve 'components/MovieCard'
VS终端报错
No ModuleFederationPlugin(s) found. error - ./pages/index.js:3:35 Module not found: Can't resolve 'components/MovieCard'
问题修复方案
修正Remote URL的拼写错误
home项目的remotes配置中,URL少了一个冒号,正确的URL应该是http://localhost:3001/.next/static/chunks/remoteEntry.js,修改后的配置片段:remotes: { components: "components@http://localhost:3001/.next/static/chunks/remoteEntry.js" }确保远程项目先启动
先启动reactcomponents项目(确保它运行在3001端口),再启动home项目,保证remoteEntry.js文件可以被正常访问。验证组件引用路径
在home项目的页面中引用组件时,确保路径与reactcomponents中exposes配置的路径一致,比如:import MovieCard from 'components/MovieCard';添加必要的共享依赖(可选)
如果两个项目有共同依赖(比如React、ReactDOM),可以在两个项目的NextFederationPlugin配置中添加shared字段,避免重复打包:shared: { react: { singleton: true, eager: true }, 'react-dom': { singleton: true, eager: true } }
内容的提问来源于stack exchange,提问作者Souvik Banerjee
相关产品推荐
相关产品推荐

