Vite.js+TS+模块联邦基础配置失效,报组件类型无效错误
报错信息
Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check your code at main.tsx:7.
Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
问题分析
该报错本质是组件导入后为undefined,结合模块联邦场景,大概率是模块解析路径不匹配或共享依赖配置不当导致组件加载失败。
解决方案
1. 修正模块联邦暴露路径
在vite.config.ts中补充暴露组件的完整扩展名,确保模块联邦能正确定位文件:
export default defineConfig({ // 其他配置保留 plugins: [ react(), federation({ name: 'my_app', filename: 'remoteEntry.js', // 修改暴露路径,添加.tsx扩展名 exposes: { './Initializer': './src/Initializer.tsx', }, // 共享依赖配置后续调整 }), ], })
2. 优化共享依赖配置
React和ReactDOM必须保证单例,否则会出现跨模块实例冲突,修改共享依赖配置:
shared: { react: { singleton: true, // 强制单例模式 requiredVersion: '^18.2.0', // 匹配当前项目依赖版本 }, react-dom: { singleton: true, requiredVersion: '^18.2.0', }, },
3. 统一本地导入路径
将main.tsx中的导入路径简化,与模块联邦暴露路径保持一致,避免扩展名差异引发解析问题:
// 原导入:import Initializer from "./Initializer.tsx"; // 修改为: import Initializer from "./Initializer";
4. 清除缓存并重启服务
执行以下操作确保配置生效:
- 删除
dist文件夹 - 运行
npm run build重新构建 - 重启开发服务
npm start
内容的提问来源于stack exchange,提问作者GoRobotFlame

