DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Adding locally hosted Google fonts to your SvelteKit project
Stanislav Khromov
Stanislav Khromov

Posted on • Updated on • Originally published at khromov.se

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 @fontsource/roboto
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Read more: Official Fontsource documentation.

Photo by Brett Jordan on Unsplash

Top comments (3)

Collapse
 
mandrasch profile image
Matthias Andrasch

Hey, thanks for sharing! πŸ‘ Do you happen to know if this can be easily combined with Tailwind in SvelteKit projects? :)

Collapse
 
khromov profile image
Stanislav Khromov

πŸ‘‹ I didn't try it with Tailwind, but since the fonts are included globally in your application via the +layout.svelte file, it should work as long as the font-family matches in the resulting Tailwind CSS rule.

Collapse
 
douganderson444 profile image
Doug A

Yes it can, I just did it. You just have to install postcss-import and add it to your postcss.config.cjs file. Then in app.css you can @import

Become a Moderator Do you want us to help make DEV a better place?

Fill out this survey and help us by becoming a tag moderator here at DEV.