Adding locally hosted Google fonts to your SvelteKit project
When you add fonts to your SvelteKit projects, you ideally want to do it in a privacy-friendly way. This means not loading the fonts from an external CDN and instead hosting them locally, or on a CDN that you control.
To do this with SvelteKit, you can use the Fontsource project. They host all of the Google Fonts catalogue as NPM packages.
Let’s say that we want to use the Roboto font.
Install the font
npm i -D @fontsource/roboto
Load the font
We want to load the font somewhere globally so it’s available to all your components. A great place for this is your src/routes/+layout.svelte
file.
Let’s add our font:
<script>
import "@fontsource/roboto";
</script>
Now we can use it anywhere in our application. Let’s say we have a HelloWorld.svelte
component:
<style>
h1 {
font-family: 'Roboto', sans-serif;
}
</style>
<h1>Hello world in Roboto!</h1>
If we want to use a different font weight, we can first consult the Roboto font page on Fontsource. There we can see that Roboto supports a number of weights, such as 300, 400 and 700. By default when importing a font you will typically get the 400 weight. If we want to use the 400 and the 700 variant, we can import both of them:
<script>
import "@fontsource/roboto/400.css";
import "@fontsource/roboto/700.css";
</script>
Then in our component we style using these weights:
<style>
h1, h2 {
font-family: 'Roboto', sans-serif;
}
h1 {
font-weight: 400;
}
h2 {
font-weight: 700;
}
</style>
<h1>Hello world normal weight!</h1>
<h2>Hello world in bold weight!</h2>
Read more: Official Fontsource documentation.
Photo by Brett Jordan on Unsplash
View Comments
Build your Capacitor Android app bundle using GitHub Actions
Looking for building iOS bundles with Capacitor? Check out this blog post instead!...
sounak
AuthorHi Stanislav, very informative post. However, could you help/guide me in the following aspects –
1. How to add multiple fonts in sveltekit using fontsource
2. How to add the fonts to the tailwind config file?
Stanislav Khromov
AuthorHi sounak!
To add multiple fonts, install the package for each font you want, and import them one by one, like:
import “@fontsource/roboto”;
import “@fontsource/aboreto”;
Regarding Tailwind I don’t know because I don’t use it, but some people were discussing it on the dev.to version of this post, there were some suggestions:
https://dev.to/mandrasch/comment/22pbm