Reputation: 2947
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?
Upvotes: 8
Views: 12103
Reputation: 179
This answer is the updated version of @sudo bangbang's answer
Head to any font that you wish to apply in your CSS, click the Download family
to get a zip file.
Extract the zip file and move the folder into the src folder as below.
After that, refer to the below code, modify the src
to the correct URL and put in the correct format
. Here I used truetype
, based on MDN
The available types are: "woff", "woff2", "truetype", "opentype", "embedded-opentype", and "svg".
The font-family
attribute is the custom name. You can put any name you want.
@font-face {
font-family: 'primary-font';
src: url(./fonts//Sriracha/Sriracha-Regular.ttf) format('truetype');
}
.primary-font {
font-family: primary-font;
}
@fontsource
Since Typefaces project is now deprecated, we can use the alternative package by the same author FontSource
Let me use Poppins
as an example.
First, download the package
npm install @fontsource/poppins --save
Next import the package in your index.js
file
import "@fontsource/poppins";
Then use it as you wish
.primary-font {
font-family: "Poppins";
}
Supported font list is in this Github repo directory.
Upvotes: 3
Reputation: 28229
There are multiple ways of doing this.
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.
You can download fonts from fonts.google.com
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.
Upvotes: 15