A
A
Alexander2021-06-05 15:12:26
css
Alexander, 2021-06-05 15:12:26

How to add fonts to styled components?

Hello, please tell me why fonts are not added to the create-react-app application?
The fonts are in the src/fonts/ folder.
There are no errors when connecting, what could be the problem?

import styled, { createGlobalStyle } from 'styled-components'

export function fontFace(
  name: string,
  src: string,
  fontWeight: number | string = 'normal',
  fontStyle: string = 'normal'
) {
  /* eslint-disable */
  return `
    @font-face{
        font-family: "${name}";
        src: url(${require('../fonts/' + src + '.eot')});
        src: url(${require('../fonts/' + src + '.eot')}?#iefix) format("embedded-opentype"),
             url(${require('../fonts/' + src + '.woff')}) format("woff"),
             url(${require('../fonts/' + src + '.ttf')}) format("truetype"),
        font-style: ${fontStyle};
        font-weight: ${fontWeight};
    }
`
}

export const GlobalStyle = createGlobalStyle`
  ${fontFace('OswaldRegular', 'Oswald-Regular', 'normal', 'normal')}

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
li {
  list-style: none;
}

a {
  text-decoration: none;
}
body {
  font-family: 'OswaldRegular';

}
`

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WbICHA, 2021-06-07
@WblCHA

So no one answered ...
I don’t remember exactly, but definitely not through require. You need to write the path as a string. The path must be relative to the public folder (this is the root folder for the application).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question