如何在MUI v5中更优雅简洁地配置使用可变字体?
MUI v5 可变字体主题配置简化方案
方案1:抽离公共配置 + 工厂函数批量注入(最低改造成本)
先把重复的可变字体兼容逻辑抽成公共常量和生成函数,所有变体直接复用逻辑,不需要重复写@supports块:
// 提前计算好可变字体族,避免重复执行join const variableFontFamily = variableSystemFonts.join(","); // 公共可变字体兼容配置 const variableFontBaseConfig = { "@supports (font-variation-settings: normal)": { fontFamily: variableFontFamily, } }; // 变体配置生成函数,支持自定义可变字重 const createTypographyVariant = (baseProps, variableWeight = null) => { const variantConfig = { ...baseProps, ...variableFontBaseConfig }; if (variableWeight) { variantConfig["@supports (font-variation-settings: normal)"].fontVariationSettings = `'wght' ${variableWeight}`; } return variantConfig; };
改造后的typography配置如下:
typography: { fontFamily: systemFonts.join(","), fontWeightExtraBold: 800, h1: createTypographyVariant({ fontSize: "clamp(2.625rem, 1.2857rem + 3.5714vw, 4rem)", fontWeight: 800, lineHeight: 78 / 70, }, 800), h2: createTypographyVariant({ fontSize: "clamp(1.5rem, 0.9643rem + 1.4286vw, 2.25rem)", fontWeight: 800, lineHeight: 44 / 36, }, 800), h3: createTypographyVariant({ fontSize: defaultTheme.typography.pxToRem(36), lineHeight: 44 / 36, letterSpacing: 0, }), // 其余变体直接套用createTypographyVariant即可 }
方案2:全局组件样式覆盖(更适合全项目统一可变字体规则)
如果所有Typography变体都需要应用可变字体兼容,直接在主题的组件全局样式里配置,不需要在typography变体中重复声明:
const theme = createTheme({ typography: { fontFamily: systemFonts.join(","), fontWeightExtraBold: 800, h1: { fontSize: "clamp(2.625rem, 1.2857rem + 3.5714vw, 4rem)", fontWeight: 800, lineHeight: 78 / 70, }, h2: { fontSize: "clamp(1.5rem, 0.9643rem + 1.4286vw, 2.25rem)", fontWeight: 800, lineHeight: 44 / 36, }, h3: { fontSize: defaultTheme.typography.pxToRem(36), lineHeight: 44 / 36, letterSpacing: 0, }, // 其余变体正常编写即可,无需加@supports块 }, components: { MuiTypography: { styleOverrides: { root: { "@supports (font-variation-settings: normal)": { fontFamily: variableSystemFonts.join(","), } }, // 仅需要自定义可变字重的变体单独配置即可 h1: { "@supports (font-variation-settings: normal)": { fontVariationSettings: "'wght' 800" } }, h2: { "@supports (font-variation-settings: normal)": { fontVariationSettings: "'wght' 800" } } } } } })
这种方案会让typography变体的配置更清爽,公共的可变字体族规则全局生效,仅需要给特殊字重的变体单独配置可变参数即可。
内容的提问来源于stack exchange,提问作者Matthew Kwong
相关产品推荐
相关产品推荐

