Add Custom Fonts to Storybook

React-storybook custom font handling



I will start first by asking, What is Storybook?

You knew that already then you could skip this upcoming part.

Storybook is an open source tool for developing UI components in isolation for React, Vue, and Angular. It makes building stunning UIs organized and efficient.

Installing Storybook for react apps:

npx -p @storybook/cli sb init — type react

This will check your app and start to install all required dependencies for your app, add stories dir and .storybook for config your storybook, also two scripts in package.json one for storybook in Development and another one for build storybook in Production.

  "scripts": {
    "storybook": "start-storybook -p 6060",
    "build-storybook": "build-storybook"

Running yarn storybookto start your terminal on port: 6060.

You’ll your component normally without the custom fonts if you have one, than it will come to the purpose of this article.

Add Custom Fonts

Let’s say that in your app have a custom font for me as an example will be


I have it under src/styles/ArmWrestler.woff

What we need to do first to storybook to add these files is:

1. Create webpack.config.js inside .storybook directory and Add this code to it:
const path = require('path');

module.exports = async ({ config }) => {
  // styles
    test: /\.(sass|scss)$/,
    use: ['resolve-url-loader'],     include: path.resolve(__dirname, '../')
  // fonts
    test: /\.(png|woff|woff2|eot|ttf|svg)$/,
    use: [
        loader: 'file-loader',
        query: {
          name: '[name].[ext]'
    include: path.resolve(__dirname, '../')
  // don't forget to return.
  return config;

```What that says it will take config that comes from storybook and push my custom handling for fonts with it means that configs will be merged together __This is not overriding__.

first, one for styling to handle fonts inside any scss files.
A second one for bundling my custom fonts with storybook.

###### 2.Add head Html for storybook by creating a file inside your `.storybook` called:
`preview-head.html` and put this in it:

<style type="text/css">
  @font-face {
    font-family: 'ArmWrestler';
    src: url('styles/ArmWrestler.woff') format('woff'),
      url('styles/ArmWrestler.woff2') format('woff2');
    font-weight: normal;
    font-style: normal;

What that says to take fonts inside my styles/and inject in the head of iframe.html that will be generated from storybook, check the condole.

3. Update package.json for watching styling in my app Like below:
"storybook": "start-storybook -p 6060 -c .storybook watch-css -s ./src",

With that, everything is done, your stories should pick the font the same as in the real web app.

If you would like to see more blogs, subscribe, and share in your network. I aslo have it explained on youtube if you prefer video way .ippA

Links: YouTube , Code:Github

Published on CodeReview by Mustafa Alroomi on 06-April-2020