You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MUI主题文件中配置@font-face替代index.css设置

将@font-face迁移至MUI Theme.js的实现方案

要把原index.css中的自定义字体配置完全迁移到MUI的theme.js,可以按以下步骤操作:

1. 导入MUI相关模块

在theme.js里引入必要的MUI工具:

import { createTheme, GlobalStyles } from '@mui/material/styles';

2. 定义全局字体加载样式

通过GlobalStyles组件注入原@font-face规则,实现全局加载自定义字体:

const GlobalFontStyles = () => (
  <GlobalStyles styles={`
    @font-face {
      font-family: 'ATTAleckSans_W_Lt';
      src: url('./fonts/ATTAleckSans_W_Lt.woff2');
      // 可按需补充字体属性,比如:
      // font-weight: 300;
      // font-style: normal;
    }
  `} />
);

3. 配置Theme的默认字体

在createTheme中设置全局默认字体族为你的自定义字体,让所有MUI组件默认使用该字体:

const theme = createTheme({
  typography: {
    fontFamily: "'ATTAleckSans_W_Lt', sans-serif",
  },
  // 若需给特定组件单独指定字体,可在components字段配置,示例:
  // components: {
  //   MuiButton: {
  //     styleOverrides: {
  //       root: {
  //         fontFamily: "'ATTAleckSans_W_Lt', sans-serif",
  //       },
  //     },
  //   },
  // },
});

// 导出theme和全局字体样式组件
export { theme, GlobalFontStyles };

4. 在应用根组件中启用配置

在应用入口文件(比如App.js)中,同时使用ThemeProvider和GlobalFontStyles:

import { ThemeProvider } from '@mui/material/styles';
import { theme, GlobalFontStyles } from './theme';

function App() {
  return (
    <ThemeProvider theme={theme}>
      <GlobalFontStyles />
      {/* 放置你的应用内容 */}
    </ThemeProvider>
  );
}

export default App;

完成以上操作后,即可完全弃用原index.css文件,自定义字体将通过MUI的Theme系统全局生效。

内容的提问来源于stack exchange,提问作者ram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:54:25