如何在Next.js 13+Material UI中用next/font全局配置两种Google字体
实现Next 13 + MUI 5全局配置自定义字体
步骤1:导入并配置next/google字体
在你的根布局文件(App Router用app/layout.tsx,Pages Router用_app.tsx)中,导入目标字体并生成实例:
import { Rubik, Ephesis } from 'next/font/google'; // 配置Rubik字体,按需指定字重 const rubik = Rubik({ subsets: ['latin'], weight: ['300', '400', '500', '700'], variable: '--font-rubik', // 定义CSS变量用于全局引用 }); // 配置Ephesis字体(该字体仅支持400字重) const ephesis = Ephesis({ subsets: ['latin'], weight: ['400'], variable: '--font-ephesis', });
步骤2:全局注入字体样式
在布局的根HTML元素上添加字体生成的变量类名,让字体样式全局生效:
export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang="zh-CN" className={`${rubik.variable} ${ephesis.variable}`}> <body>{children}</body> </html> ); }
步骤3:修改MUI主题,映射字体名称
在MUI主题配置文件(比如src/theme.ts)中,将字体名称加入主题配置,让Typography组件能直接识别:
import { createTheme } from '@mui/material/styles'; const theme = createTheme({ typography: { // 设置默认全局字体为Rubik fontFamily: ['Rubik', 'sans-serif'].join(','), // 自定义Ephesis字体的映射项 fontFamilyEphesis: '"Ephesis", cursive', }, // 或者通过组件样式覆盖,直接识别"Ephesis"字符串 components: { MuiTypography: { styleOverrides: { root: { '&[style*="fontFamily: Ephesis"]': { fontFamily: '"Ephesis", cursive', }, }, }, }, }, }); export default theme;
步骤4:应用主题并验证
在布局组件中引入ThemeProvider,将修改后的主题传入:
import { ThemeProvider } from '@mui/material/styles'; import theme from '@/src/theme'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang="zh-CN" className={`${rubik.variable} ${ephesis.variable}`}> <body> <ThemeProvider theme={theme}> {children} </ThemeProvider> </body> </html> ); }
现在你可以像之前一样直接使用:
<Typography fontFamily='Ephesis' children='Hi' />
也可以通过主题变量引用:
<Typography fontFamily={theme.typography.fontFamilyEphesis} children='Hi' />
内容的提问来源于stack exchange,提问作者xandert.93
相关产品推荐
相关产品推荐

