How to self host a font from Google Fonts, the easy way, via NPM
In one of my previous posts (How to self host a web font from google fonts) , I taught you how to do it manually.
The advantage to doing it this way instead of hot linking is speed and privacy.
It turns out that there is an easier way to do it, with NPM.
Here's how to do it.
Setup NPM
Note
Only do this if you haven't set up NPM for this already
- Run
npm init. - Add node_modules to .gitignore (or equivelent).
- Other developers (or CI) should run
npm cibefore using your code.
Get the font package name and install the font
Note
This guide is designed for variable fonts. The steps should be simaler for non variable fonts.
- Go to fontsource.org, and search for the font you want(eg
Google Sans Flex). - Click on "Get Font".
- Click on "Developer Setup".
- It should give you a command like
npm install @fontsource-variable/google-sans-flex; run that command. - Copy the part after
npm install(eg copy@fontsource-variable/google-sans-flex); this will now be refered to as $FONT_PACKAGE. - There should be a folder
./node_modules/$PACKAGE_NAME. If you have a SSG or something, set that folder (and the files subdirectory) to passthrough
Start using the font.
- Decide which axis to use. For this example, we will only use wght.
- For each axis, import the CSS from
./node_modules/PACKAGE_NAME.
For this blog, we do:
<link rel="stylesheet" href="/node_modules/@fontsource-variable/google-sans-flex/wght.css">
- Ensure that your use of the font is license compliant. (the license is in
./node_modules/PACKAGE_NAME/LICENSE; you may have to link to it) - Find the name used for the font-family from from the font-family rule in the CSS you are importing.
- Using the font-family CSS rule, use the font.