Lewislbr

Add fonts to a React with styled-components, TypeScript and webpack project

In this post we'll see how to add custom fonts to a styled-components-based frontend project.

Get Font Files

Have a .woff2 version (at least) of the font you want to use. This will ensure a good performance and browser coverage without using many files. We can add more formats like .woff, .ttf, .otf, and .eot for greater coverage.

Set Up Global Styles

We can use the createGlobalStyle helper function from styled-components that will define the styles that affect the whole application, and import the fonts directly from their location to use with the font-face CSS rule:

import {createGlobalStyle} from "styled-components"
import FontName400 from "../assets/fonts/FontName400.woff2"

export const GlobalStyles = createGlobalStyle`
  @font-face {
    font-family: Font Name;
    font-style: normal;
    font-weight: 400;
    src: url(${FontName400});
  }
`

Declare The Font Format In TypeScript

TypeScript will give an error that it doesn't find the module of the imported fonts. To fix it, we have to add a declaration in the .d.ts file of our project with the extension of the font files.

declare module "*.woff2"

Configure webpack

To add the fonts in the final bundle, we need to install file-loader, which will allow webpack to process different kind of files.

npm i -D file-loader

Once installed, we can add to the webpack configuration file the specific types of fonts we want to use with it:

module.exports = {
  module: {
    rules: [
      {
        test: /\.(woff2|woff|eot|ttf|otf)$/,
        use: ["file-loader"],
      },
    ],
  },
}

And that's it! Additionaly, make sure to have a good variety of fallback fonts in case the loading is slow, and an optimal font-display value for your needs.



If you're using dark mode, do you like the code blocks's theme? I have it available for VS Code, feel free to check it.