Gatsby Typography
June 22, 2020
How to import custom fonts in Gatsby
You can find information on how to set up gatsby typography on gatsbyjs.org.
This forum is built by Gatsby and I used two main fonts families. The first is the “Courier New” font family and the second is the “Montserrat” one.
The main reason I wrote this guide is because “Courier New” is not open source and is not part of the google fonts.
In order to use it we have to upload it directly from our blog assets folder.
I found the following method on stack overflow:
We need to add the folder containing our font/s in gatsby-config.js
plugin: [{
resolve: \gatsby-source-filesystem`,
options: {path: `${__dirname}/assets/font`,},
},]`
then I added the font family to my css fonts.css:
u/font-face {
font-family: 'Courrier New';
font-style: normal;
font-weight: lighter;
src: url("../font/CourrierNew.ttf") format("truetype");
}
//use format("woff") for woff format
this approach was easy and worked fine for the “Courier New” family as the file size is 27kb.
The “Montserrant” family font file size is over 240kb. Despite nowaday most people have fast internet connections we should alway try to minimize the size of our files.
Luckily there is a NPM package called typeface we can use to import most of the open source font family in our project.
The package is easy to install. From your terminal use the following command:
npm: npm install --save typeface-open-sans
yarn: yarn add typeface-open-sans
you need to replace “open-sans” with the name of the family you need to install, you can find the list of the supported font family and more on the git page project.
Once you install our family font we can import it directly in our pages import 'typeface-open-sans' or in the app entry file require("typeface-open-sans")
Difference in size
We should always use typeface when we can. I tested both methods above with the ‘Montserrant’ family font as it is an open source and we can download from google font.
Lighthouse performance benchmark using the former solution stopped at 71%, using typeface with no other code chages brought the performance to 90%.