Stanislav Khromov

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 @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

Web Developer at Aftonbladet (Schibsted Media Group)

View Comments

There are currently no comments.

Next Post