United Kingdom: +44 (0)208 088 8978

Using open fonts in SAFE

Matt shows how easy it is to add open-source fonts to a SAFE Stack app.

We're hiring Software Developers

Click here to find out more

Ever wanted to spice up your SAFE app with a cool new font? Thanks to an abundance of open-source fonts and a handy GitHub project, it's easy to do just that! I'll show you how in this post.

Fontsource

Just like software, there's a massive ecosystem of open-source fonts. Fontsource is an "updating monorepo full of self-hostable Open Source fonts bundled into individual NPM packages!" This means that there's a GitHub repo where the community can come together to create NPM packages, each of which contains an open-source font, with more packages being added regularly. You can search for fonts on the Fontsource website, which also includes links to the each font's license.

For example, the @fontsource/astloch package contains the rather nifty-looking Astloch font, licensed under the SIL Open Font License

Sample text in the Astloch font

Using a Fontsource font from your SAFE app

  1. Install the Astloch font.

    npm install @fontsource/astloch
  2. Add ./src/Client/style.scss, referring to the new font.

    .fancy-text {
        font-family: "Astloch", cursive;
        color: red;
    }
  3. Modify ./webpack.config.js to use the new SCSS file.

    • Add a cssEntry variable to the CONFIG object:

      cssEntry: './src/Client/style.css',
    • Find the entry field in the module.exports object, and replace it with the following:

      entry: isProduction ? {
       app: [resolve(CONFIG.fsharpEntry), resolve(CONFIG.cssEntry)]
      } : {
       app: resolve(CONFIG.fsharpEntry),
       style: resolve(CONFIG.cssEntry)
      },
    • Change the rule that handles font files to use the asset module by replacing

      {
       test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)(\?.*)?$/,
       use: ['file-loader']
      },

      with

      {
       test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)(\?.*)?$/,
       type: 'asset'
      },
  4. Use the new CSS class in client code. For example, modify ./src/Client/Index.fs by replacing

    for todo in model.Todos do
       Html.li [ prop.text todo.Description ]

    with

    for ix, todo in model.Todos |> List.indexed do
       Html.li [
           if ix = 0 then prop.className "fancy-text"
           prop.text todo.Description
       ]

With those changes made, the new font should appear in your app.

SAFE todos with first item in a different font

Wrap up

That's it! Fontsource makes it easy to download many open-source fonts, and integrating them into a SAFE app doesn't take much effort.

A new font can add some pizzazz to your app. Judiciously applied, careful use of fonts can enhance its user experience. I hope that this post has made you excited to try some new fonts out!