NextJS+React项目Material UI Select重载页面报错:import语句模块外使用
解决NextJS项目重载Material UI Select页面时的SyntaxError问题
问题说明
基于NextJS+React+Node搭建的项目运行正常,但重载包含Material UI Select组件的页面时,抛出错误:SyntaxError: Cannot use import statement outside a module,错误来自node_modules中的@mui/material依赖。当前Select的导入方式为:
import Select from '@mui/material/Select/Select';
组件代码如下:
<Select defaultValue='#' onChange={e => setCommunityCode(e.target.value)} labelId='communityLabel'> <MenuItem value='#' hidden={true}></MenuItem> {communities.map(community => ( <MenuItem value={community.id} key={community.id}> {community.id + ' - ' + community.name} </MenuItem> ))} </Select>
解决方案
1. 修正Select导入路径(优先推荐)
不要直接导入Material UI内部的Select/Select文件,改用官方推荐的导入方式:
- 方式一:
import Select from '@mui/material/Select';
- 方式二:
import { Select } from '@mui/material';
原因:Material UI的顶层/二级导出文件是经过编译适配的,直接访问深层子目录会拿到未处理的ES模块源码,NextJS在页面重载的服务端渲染环节无法正确识别这些模块,从而抛出错误。
2. 配置NextJS转译Material UI包(仅特殊场景使用)
如果因需求必须保留深层导入,需在next.config.js中添加transpilePackages配置,让NextJS转译@mui/material的文件:
/** @type {import('next').NextConfig} */ const nextConfig = { transpilePackages: ['@mui/material'], } module.exports = nextConfig
3. 清除项目缓存
若上述方法无效,可能是缓存导致的异常,执行以下命令清除缓存后重新构建:
rm -rf .next node_modules npm install npm run build
内容的提问来源于stack exchange,提问作者khandoras
相关产品推荐
相关产品推荐

