How to add custom font using @fontface to Storybook? (Need updated answer for storybook version 6.5.5)?

Viewed 95

I have tried all the solutions available online to add custom font in the Storybook but failed. Following are the files under .storybook folder that I have added as per this solution:

  1. webpack.config.js :

const path = require('path');

module.exports = async ({ config }) => {
  // fonts
  config.module.rules.push({
    test: /\.(png|woff|woff2|eot|ttf|svg)$/,
    use: [
      {
        loader: 'file-loader',
        options: {
          name: '[name].[ext]',
        },
      },
    ],
    include: path.resolve(__dirname, '../'),
  });

  return config;
};

  1. preview.head.html

<style type="text/css">
  @font-face {
    font-family: 'Eina';
    src: url('../src/styles/Eina03-Regular.ttf') format('truetype');
    font-weight: 400;
    font-style: normal;
  }
  @font-face {
    font-family: 'Eina';
    src: url('../src/styles/Eina03-SemiBold.ttf') format('truetype');
    font-weight: 600;
    font-style: normal;
  }
  @font-face {
    font-family: 'Eina';
    src: url('../src/styles/Eina03-Bold.ttf') format('truetype');
    font-weight: 700;
    font-style: normal;
  }
</style>

  1. main.js

const path = require('path');

module.exports = {
  stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
  staticDirs: ['../public', '../public/fonts'],
  addons: [
    '@storybook/addon-links',
    '@storybook/addon-essentials',
    '@storybook/addon-interactions',
    {
      name: '@storybook/addon-postcss',
      options: {
        postcssLoaderOptions: {
          implementation: require('postcss'),
        },
      },
    },
  ],
  framework: '@storybook/react',
  core: {
    builder: 'webpack5',
  },
  webpackFinal: async config => {
    config.module.rules.push({
      test: /\.scss$/,
      use: ['style-loader', 'css-loader', 'sass-loader'],
      include: path.resolve(__dirname, '../'),
    });

    return config;
  },
};

The font is stored in src/styles/. Also, I already have main.js file so I ignored the config.js, which needed to be added as per the solution

Any help will be highly appreciated.

0 Answers
Related