Search code examples
cssgatsbywebfonts

How to import local fonts into a Gatsby website?


To begin, I know that's probably a silly one. Fonts always give me trouble, somehow such a common thing is really not easy to find information on. All tutorials online make it look extremely easy (including Gatsby's own), no one really covers potential issues.

I'm using this guide, it's simple, but it gives an idea: declare @font-face in a separate CSS file, import that file in your app. So here's my structure:

src/
┣ assets/
┃ ┗ fonts/
┃   ┣ DMSerifDisplay-Italic.ttf
┃   ┣ DMSerifDisplay-Regular.ttf
┃   ┗ fonts.css
┣ components/
┃ ┣ ...
┃ ┗ layout.tsx
┗ pages/
  ┣ 404.tsx
  ┗ index.tsx

Both fonts are imported in fonts.css like this:

@font-face {
  font-family: 'DM Serif Display';
  src: url('./DMSerifDisplay-Regular.ttf') format('ttf');
}
@font-face {
  font-family: 'DM Serif Display';
  font-style: italic;
  src: url('./DMSerifDisplay-Italic.ttf') format('ttf');
}

Then that file is imported in layout.tsx (which is the basis of any page):

import React, { FC } from 'react'
import { Header } from './header'
import { Footer } from './footer'
import { GlobalStyles } from './global-styles'
import { ThemeProvider } from 'styled-components'
import { theme } from './sc-theme'
import '../assets/fonts/fonts.css'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

export const Layout: FC = ({ children }) => {
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyles />
      <Header />
      <main>{children}</main>
      <Footer />
    </ThemeProvider>
  )
}

However, I don't see the fonts be imported in the network tab. I tried adding some styles into fonts.css and they do indeed load, so the file is there in the bundle, but not the fonts. Let me know if any other information would help.


Solution

  • Can you try that?

    @font-face {
      font-family: 'DM Serif Display';
      src: local('DM Serif Display'), url('./DMSerifDisplay-Regular.ttf') format('truetype');
    }
    
    @font-face {
      font-family: 'DM Serif Display';
      font-style: italic;
      src: local('DM Serif Display'), url('./DMSerifDisplay-Italic.ttf') format('truetype');
    }