Vite SSR构建引入MUI图标与日期选择器时失败报错
Vite SSR + MUI 构建后服务器报错解决方案
一、日期选择器(AdapterDayjs)构建报错
报错场景
开发模式下导入AdapterDayjs正常,构建后服务器启动抛出连续错误:
- 初始错误:
file:///xxx/dist/server/entry-server.js:4 import { AdapterDayjs} from "@mui/x-date-pickers/AdapterDayjs/index.js"; ^^^^^^^^^^^^ SyntaxError: Named export 'AdapterDayjs' not found. The requested module '@mui/x-date-pickers/AdapterDayjs/index.js' is a CommonJS module, which may not support all module.exports as named exports.
- 按提示改用默认导入后,触发新错误:
export { AdapterDayjs } from './AdapterDayjs'; ^^^^^^ SyntaxError: Unexpected token 'export'
解决方案
使用MUI为Node环境提供的专属入口路径导入:
import { AdapterDayjs } from "@mui/x-date-pickers/node/AdapterDayjs";
原因分析
@mui/x-date-pickers默认入口的代码在SSR构建时存在模块格式混合问题,Node无法正确解析ES模块语法。而/node子路径下的代码是专门为Node环境优化的兼容版本,适配Vite SSR的模块解析逻辑。
二、MUI图标构建后渲染报错
报错信息
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
解决方案
方案1:调整Vite SSR配置
在vite.config.js中修改模块解析条件:
export default defineConfig({ // ...其他配置 ssr: { resolve: { conditions: ['node', 'import'] }, // 若上述配置无效,可尝试将图标包加入非外部依赖 // noExternal: ['@mui/icons-material'] } })
方案2:修正图标导入方式
确保使用默认导入(MUI图标为默认导出组件),避免错误的命名导入:
// 正确 import HomeIcon from '@mui/icons-material/Home'; // 错误(会导致导出为对象而非组件) import { HomeIcon } from '@mui/icons-material/Home';
原因分析
Vite SSR构建时,若未正确配置模块解析条件,@mui/icons-material的ES模块会被错误解析为CommonJS对象,导致React渲染时无法识别为有效组件类型。
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

