How to config webpack to load custom fonts into storybook?

Member

by domenico , in category: Javascript , 9 months ago

How to config webpack to load custom fonts into storybook?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , 9 months ago

@domenico 

To configure Webpack to load custom fonts into Storybook, you can follow these steps:

  1. First, install file-loader which is required to load font files in Webpack:
1
npm install file-loader --save-dev


  1. Create a new file named webpack.config.js in your Storybook project directory.
  2. Add the following configuration to the webpack.config.js file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
module.exports = async ({ config }) => {
  config.module.rules.push({
    test: /.(woff|woff2|eot|ttf|otf)$/,
    use: [
      {
        loader: 'file-loader',
        options: {
          name: '[name].[ext]',
          outputPath: 'fonts/'
        }
      }
    ]
  });

  return config;
};


  1. Update your Storybook configuration file to use webpack.config.js by adding the following line at the top of the file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const path = require('path');

module.exports = {
  webpackFinal: async (config, { configType }) => {
    config.module.rules.push({
      test: /.(woff|woff2|eot|ttf|otf)$/,
      use: ['file-loader']
    });

    return config;
  },
};


  1. Restart your Storybook server:
1
npm start


Now, you should be able to import and use custom fonts in your Storybook components. Just make sure to place your font files in the correct directory and import them into your CSS or SCSS files.