Fully include Google web font in create-react-app build (without ejecting)

code_onkel picture code_onkel · Sep 18, 2018 · Viewed 9k times · Source

I need to include a Google web font in the build of a React webapp using create-react-app. This is, because the app will be served on a wifi without internet access. The most straightforward solution seems to be google-fonts-webpack-plugin, but it needs a customized webpack config.

Is there any "simple" solution that downloads and includes all the web font resources automagically without the requirement to eject from create-react-app?

Answer

sudo bangbang picture sudo bangbang · Sep 18, 2018

There are multiple ways of doing this.

1. Importing font

For example, for using Roboto, do

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. Download the font manually and add it to stylesheet

You can download fonts from fonts.google.com

fonts.google.com page

Now, you can put the font in src/fonts/Lato.woff, and use it in your index.css.

@font-face {
    font-family: 'Lato';
    src: local('Lato'), url(./fonts/Lato.woff) format('woff');
}

For ttf font, you should give truetype instead of ttf as the parameter to the format

You can import this to your index.js to make it available

import './index.css';

You can do these in App.css, App.js as well. It's your preference.