How to add fonts to create-react-app based projects?

前端 未结 7 1771
长情又很酷
长情又很酷 2020-11-29 15:19

I\'m using create-react-app and prefer not to eject.

It\'s not clear where fonts imported via @font-face and loaded locally should go.

Namely,

7条回答
  •  北海茫月
    2020-11-29 15:48

    Here are some ways of doing this:

    1. Importing font

    For example, for using Roboto, install the package using

    yarn add typeface-roboto
    

    or

    npm install typeface-roboto --save
    

    In index.js:

    import "typeface-roboto";
    

    There are npm packages for a lot of open source fonts and most of Google fonts. You can see all fonts here. All the packages are from that project.

    2. For fonts hosted by Third party

    For example Google fonts, you can go to fonts.google.com where you can find links that you can put in your public/index.html

    It'll be like

    
    

    or

    
    

    3. Downloading the font and adding it in your source code.

    Download the font. For example, for google fonts, you can go to fonts.google.com. Click on the download button to download the font.

    Move the font to fonts directory in your src directory

    src
    |
    `----fonts
    |      |
    |      `-Lato/Lato-Black.ttf
    |       -Lato/Lato-BlackItalic.ttf
    |       -Lato/Lato-Bold.ttf
    |       -Lato/Lato-BoldItalic.ttf
    |       -Lato/Lato-Italic.ttf
    |       -Lato/Lato-Light.ttf
    |       -Lato/Lato-LightItalic.ttf
    |       -Lato/Lato-Regular.ttf
    |       -Lato/Lato-Thin.ttf
    |       -Lato/Lato-ThinItalic.ttf
    |
    `----App.css
    

    Now, in App.css, add this

    @font-face {
      font-family: 'Lato';
      src: local('Lato'), url(./fonts/Lato-Regular.otf) format('opentype');
    }
    
    @font-face {
        font-family: 'Lato';
        font-weight: 900;
        src: local('Lato'), url(./fonts/Lato-Bold.otf) format('opentype');
    }
    
    @font-face {
        font-family: 'Lato';
        font-weight: 900;
        src: local('Lato'), url(./fonts/Lato-Black.otf) format('opentype');
    }
    

    For ttf format, you have to mention format('truetype'). For woff, format('woff')

    Now you can use the font in classes.

    .modal-title {
        font-family: Lato, Arial, serif;
        font-weight: black;
    }
    

    4. Using web-font-loader package

    Install package using

    yarn add webfontloader
    

    or

    npm install webfontloader --save
    

    In src/index.js, you can import this and specify the fonts needed

    import WebFont from 'webfontloader';
    
    WebFont.load({
       google: {
         families: ['Titillium Web:300,400,700', 'sans-serif']
       }
    });
    

提交回复
热议问题