Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Installing Google Fonts as npm packages

Google Fonts is a great resource for finding free fonts for your web projects. It has a wide variety of fonts to choose from. You include these fonts in your project using the <link> tag or by using the @import rule in your CSS which points to the Google Fonts CDN.

The problem with this approach is that it adds an extra HTTP request (to an external service) to your page which can be avoided if you download the fonts locally and include them in your project. But, this can be a tedious task if you’re using a lot of fonts in your project. It becomes unmanageable over time.

Apart from this, there are privacy concerns involved as well since Google often pushes updates to their fonts without notice, which may interfere with your live production projects.

Enter Fontsource.

It’s an open-source project that can help you overcome all the issues mentioned above. It’s a collection of self-hosted fonts (including Google Fonts) that can be installed as npm packages.

It has a wide variety of fonts to choose from. The interface is pretty similar to Google Fonts as well.

You can search your desired fonts on Fontsource, grab the installation command, and install it using npm like so.

npm install @fontsource/roboto

Now, in your application’s entry file, page, or site component, import the font package using the package name. For example, to import Roboto into the index.jsx file, add the following code:

import "@fontsource/roboto";

And that’s it! You can now use the font in your project like so.

body {
    font-family: 'Roboto', sans-serif;
}

I think this is a pretty neat way of including fonts in your project. It’s easy to manage, privacy-friendly, and doesn’t add any extra HTTP requests to your page.

This also means that the fonts can be loaded offline as well. So, if you’re building a Progressive Web App, you can cache the fonts using a service worker and load them offline.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?