Zhanna_K
@Zhanna_K
in progress

Как правильно подключить шрифты в React (Material UI)?

Пытаюсь подключить файлы со шрифтами, пока безуспешно:

В документации вычитала следующее:
5f86be7a6b017707397205.png
Какой loader нужно использовать и где это прописывать?

1) Создаю кастомную тему, в ней подключаю шрифты
import { createMuiTheme } from "@material-ui/core/styles";
import blue from "@material-ui/core/colors/blue";
import yellow from "@material-ui/core/colors/yellow";
import MontserratWoff from "./fonts/Montserrat-Regular.woff";
import MontserratEot from "./fonts/Montserrat-Regular.eot";
import MontserratOtf from "./fonts/Montserrat-Regular.otf";
import MontserratTtf from "./fonts/Montserrat-Regular.ttf";

const montserrat = {
  fontFamily: "Montserrat",
  fontStyle: "normal",
  fontDisplay: "swap",
  fontWeight: 400,
  src: `
    url(${MontserratWoff}) format('woff')
    url(${MontserratEot}) format('eot')
    url(${MontserratOtf}) format('otf')
    url(${MontserratTtf}) format('ttf')
  `,
  unicodeRange:
    "U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF",
};

const theme = createMuiTheme({
  palette: {
    primary: {
      light: blue[500],
      main: blue[200],
      dark: blue[900],
      contrastText: "#fff",
    },
    secondary: {
      light: yellow[300],
      main: yellow[300],
      dark: yellow[800],
      contrastText: blue[900],
    },
  },
  typography: {
    fontFamily: "Montserrat",
  },
  overrides: {
    MuiCssBaseline: {
      "@global": {
        "@font-face": [montserrat],
      },
    },
  },
  spacing: [0, 4, 8, 16, 32, 64],
});

export default theme;

2) Через провайдер передаю эту тему:
function App() {
  return (
    <div className='appWrapper'>
      <div className='skew'></div>
      <ThemeProvider theme={theme}>
        <HeaderContainer />
        <Switch>
          <Route exact path='/' component={SplashPage}></Route>
          <Route exact path='/contacts' component={Contacts}></Route>
          <AuthRoute
            exact
            path='/register'
            component={RegistrationPageContainer}
          ></AuthRoute>
          <AuthRoute
            exact
            path='/auth'
            component={authPageContainer}
          ></AuthRoute>
          <ProtectedRoute
            exact
            path='/projects'
            component={ProjectsPageContainer}
          ></ProtectedRoute>
          <ProtectedRoute
            exact
            path='/projects/:id'
            component={ProjectContainer}
          ></ProtectedRoute>
          <ProtectedRoute
            exact
            path='/tasks/:id'
            component={TasksContainer}
          ></ProtectedRoute>
          <ProtectedRoute
            exact
            path='/myprojects'
            component={MyProjectsContainer}
          ></ProtectedRoute>
        </Switch>
      </ThemeProvider>
    </div>
  );
}
export default App;


3) В компонентах пишу так:
const useStyle = makeStyles((theme) => styles(theme))

где styles, это функция, возвращающая объект со стилями.
  • Вопрос задан
  • 4443 просмотра
Пригласить эксперта
Ответы на вопрос 1
@kilot5791
Может кому поможет, я подключил шрифты следующим способом:

1) Создал файл с кастомной темой theme.jsx

import { createMuiTheme } from '@material-ui/core/styles';

// Здесь импортируем шрифты
import pathRegular from './fonts/Montserrat-Regular.woff2';
import pathBold from './fonts/Montserrat-Bold.woff2';
import pathMedium from './fonts/Montserrat-Medium.woff2';
import pathSemiBold from './fonts/Montserrat-SemiBold.woff2';
import pathExtraBold from './fonts/Montserrat-ExtraBold.woff2';

// С помощью класса мы будем создавать объекты.(чтобы под каждый шрифт не писать объект вручную, может быть есть какой то способ получше, но я новичок в js)
class Font {
    constructor(fname, fstyle, fweight, furl) {
        this.fname = fname;
        this.fstyle = fstyle;
        this.fweight = fweight;
        this.furl = furl;

        return {
            fontFamily: this.fname,
            fontStyle: this.fstyle,
            fontDisplay: 'swap',
            fontWeight: this.fweight,
            src: `
                local(${this.fname}),
                url(${this.furl}) format('woff2')
            `,
            unicodeRange:
                'U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF',
        }
    }
};

const montserratRegular = new Font('Montserrat', 'normal', 400, pathRegular);
const montserratBold = new Font('Montserrat', 'normal', 700, pathBold);
const montserratSemiBold = new Font('Montserrat', 'normal', 600, pathSemiBold);
const montserratExtraBold = new Font('Montserrat', 'normal', 800, pathExtraBold);
const montserratMedium = new Font('Montserrat', 'normal', 500, pathMedium);

export const theme = createMuiTheme({
    typography: {
        fontFamily: 'Montserrat',
        fontSize: 24,
        body1: {
            fontWeight: 400
        },
        h1: {
            fontSize: 32,
            fontWeight: 700,
            color: '#444'
        } 
    },
// Если используется СssBaseline то для него нужно изменить шрифт глобально, если не используем то код ниже не пишем
    overrides: {
        MuiCssBaseline: {
          '@global': {
            '@font-face': [montserratRegular, montserratBold, montserratSemiBold, montserratExtraBold, montserratMedium],
          },
        },
      },
});

export default theme;


2) Импортируем тему в наше приложение:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

import { ThemeProvider } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';

import './index.css';
import theme from './theme'

ReactDOM.render(
  <React.StrictMode>
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <App />
    </ThemeProvider>
  </React.StrictMode>,
  document.getElementById('root')
);


3) Само приложение App.js выглядит следующим образом:

import React from 'react'
import { Typography } from '@material-ui/core';

function App() {
  return (
    <div className="App">
      <Typography>Almost before we knew it, we had left the ground.</Typography>
      <Typography variant='h1'>Almost before we knew it, we had left the ground.</Typography>
    </div>
  );
}

export default App;

PS. Несмотря на то что в документации написано что можно импортировать шрифты в формате ttf, woff и woff2, ttf шрифты у меня не подключаются с этим кодом, woff я не пробовал
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы