Material-UI的DefaultTheme触发Invalid module name in augmentation报错如何解决
问题原因
@mui/styles是MUI v5的可选遗留依赖,默认不会随@mui/material一起安装,未安装该包时TS自然无法找到对应的模块声明。- 如果你项目已经使用MUI v5默认的emotion/styled样式方案,没有用到
@mui/styles提供的makeStyles等API,你使用的这段类型扩展是不必要的,属于针对仍在使用旧样式方案的兼容配置。
解决方案
场景1:项目未使用@mui/styles(推荐)
直接删除你代码里针对@mui/styles/defaultTheme的模块声明即可。如果你的自定义neutral调色板字段需要类型支持,可以补充针对@mui/material/styles的类型扩展,完整代码如下:
import { createTheme, Theme, Palette, PaletteColor } from '@mui/material/styles' import { grey } from '@mui/material/colors' // 扩展自定义palette字段类型 declare module '@mui/material/styles' { interface Palette { neutral: PaletteColor } interface PaletteOptions { neutral: PaletteColor } } const { palette } = createTheme() const { augmentColor } = palette // Create a theme instance. export const theme: Theme = createTheme({ palette: { neutral: augmentColor({ color: { main: grey[400] } }), } })
场景2:项目确实需要使用@mui/styles的旧API
先手动安装对应依赖:npm install @mui/styles
安装完成后TS即可找到对应模块,报错自动消失。
内容的提问来源于stack exchange,提问作者user3142695
相关产品推荐
相关产品推荐

