You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vite.js+TS+模块联邦基础配置失效,报组件类型无效错误

React + Vite 模块联邦集成报错解决

报错信息

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 07:11:28