如何将Material UI v5接入Next JS v12?相比v4是否有更优方案?
Material UI 5 接入说明
能否直接沿用v4代码?
不能直接复用你现有的MUI v4接入代码,核心原因有两个:
- MUI 5的包命名空间从
@material-ui整体变更为@mui,原有导入路径全部失效 - MUI 5默认废弃了v4使用的JSS样式引擎,切换为Emotion作为默认样式方案,原有
ServerStyleSheets等服务端渲染相关API已经不再支持
更优雅的MUI 5接入方案(适配Next.js Pages Router)
1. _app.js 配置
比v4更简洁,示例如下:
import CssBaseline from '@mui/material/CssBaseline'; import { ThemeProvider, createTheme } from '@mui/material/styles'; // 可自定义主题 const theme = createTheme({ // 你的主题配置 }); function MyApp({ Component, pageProps }) { return ( <ThemeProvider theme={theme}> <CssBaseline /> <Component {...pageProps} /> </ThemeProvider> ); } export default MyApp
2. _document.js 配置
不需要再手动处理ServerStyleSheets,改用Emotion的缓存方案处理服务端样式注入:
import Document, { Html, Head, Main, NextScript } from 'next/document'; import createCache from '@emotion/cache'; import { CacheProvider } from '@emotion/react'; import createEmotionServer from '@emotion/server/create-instance'; const getCache = () => { const cache = createCache({ key: 'mui', prepend: true }); cache.compat = true; return cache; }; export default class MyDocument extends Document { render() { return ( <Html lang="zh-CN"> <Head /> <body> <Main /> <NextScript /> </body> </Html> ); } } MyDocument.getInitialProps = async (ctx) => { const originalRenderPage = ctx.renderPage; const cache = getCache(); const { extractCriticalToChunks } = createEmotionServer(cache); ctx.renderPage = () => originalRenderPage({ enhanceApp: (App) => (props) => ( <CacheProvider value={cache}> <App {...props} /> </CacheProvider> ), }); const initialProps = await Document.getInitialProps(ctx); const emotionStyles = extractCriticalToChunks(initialProps.html); const emotionStyleTags = emotionStyles.styles.map((style) => ( <style data-emotion={`${style.key} ${style.ids.join(' ')}`} key={style.key} dangerouslySetInnerHTML={{ __html: style.css }} /> )); return { ...initialProps, styles: [...initialProps.styles, ...emotionStyleTags], }; };
补充说明
如果你暂时需要兼容v4遗留的JSS样式,可以额外安装@mui/styles包,沿用原有JSS写法,但官方不再推荐这种方案,建议逐步迁移到Emotion的样式写法。
内容的提问来源于stack exchange,提问作者Ismoil Shokirov
相关产品推荐
相关产品推荐

