如何将@font-face声明从全局CSS迁移至MUI主题并支持白标字体?
迁移@font-face到MUI主题并实现白标字体定制方案
1. 移除全局CSS中的@font-face声明
直接删除index.css里的@font-face代码块,不再依赖全局样式注入字体。
2. 在CustomThemeProvider中动态注入@font-face
利用MUI的CSS-in-JS能力,结合window.theme变量动态生成字体声明,同时关联到主题配置中:
import { createTheme, ThemeProvider } from '@mui/material/styles'; import { GlobalStyles } from '@mui/material'; import React from 'react'; const CustomThemeProvider = ({ children }) => { // 从全局配置取字体参数,设置默认值兜底 const { font = { family: 'CustomFont', url: '/fonts/default-font.woff2' } } = window.theme || {}; // 动态生成@font-face样式规则 const fontFaceStyles = { '@font-face': { fontFamily: font.family, src: `url(${font.url}) format('woff2')`, fontWeight: 'normal', fontStyle: 'normal', fontDisplay: 'swap' // 避免字体加载时的空白问题 } }; // 创建MUI主题,指定全局字体族 const theme = createTheme({ typography: { fontFamily: `${font.family}, sans-serif` // 自定义字体优先,降级到系统无衬线字体 }, // 其他原有主题配置... }); return ( <ThemeProvider theme={theme}> {/* 注入动态生成的字体样式 */} <GlobalStyles styles={fontFaceStyles} /> {children} </ThemeProvider> ); }; export default CustomThemeProvider;
3. 覆盖MUI组件默认字体(无CSSBaseline时)
因为不使用CSSBaseline,部分MUI组件可能硬编码了默认字体,需要在主题的components配置里统一覆盖:
const theme = createTheme({ typography: { fontFamily: `${font.family}, sans-serif` }, components: { // 批量覆盖所有组件的字体为继承主题字体 MuiButton: { styleOverrides: { root: { fontFamily: 'inherit' } } }, MuiTypography: { styleOverrides: { root: { fontFamily: 'inherit' } } }, MuiInput: { styleOverrides: { root: { fontFamily: 'inherit' } } }, // 其他需要调整的组件同理,或根据实际业务需求针对性覆盖 } });
4. 适配自定义GlobalStyles组件
如果你的GlobalStyles.jsx中有全局字体设置,替换为继承主题字体:
// GlobalStyles.jsx import { useTheme } from '@mui/material/styles'; import { GlobalStyles } from '@mui/material'; const CustomGlobalStyles = () => { const theme = useTheme(); const globalStyles = { body: { fontFamily: theme.typography.fontFamily, // 其他原有全局样式... } }; return <GlobalStyles styles={globalStyles} />; }; export default CustomGlobalStyles;
关键注意事项
- 确保
public/config.js在React应用脚本之前加载,保证window.theme在CustomThemeProvider渲染时已存在 - 若需要支持多字重/字体样式,可从
window.theme传入多组字体路径,生成多个@font-face规则 fontDisplay: 'swap'可优化字体加载体验,避免页面加载时的文本隐形问题
内容的提问来源于stack exchange,提问作者Cactusman07
相关产品推荐
相关产品推荐

