Add .less/.scss global styles in storybook

mdrahiem

Rahimuddin

Posted on September 22, 2020

Add .less/.scss global styles in storybook

I am trying to integrate storybook tool with my react app. My app is using .less styles and I've a single file in which all the styles are written (though I am not a big fan of this practice :))

It works for v6 but I am not sure about lower versions. You guys can give it a try.

After successful installation of storybook, we have two files (main.js and preview.js) in .storybook folder. As we know main.js is the config file for storybook and preview.js is the config file for our stories.

The idea is here to include Webpack configuration in storybook.
Question: How can we do it?
Ans: Using main.js file

Step1:

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  "stories": [
    "../src/**/*.stories.mdx",
    "../src/**/*.stories.@(js|jsx|ts|tsx)"
  ],
  "addons": [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@storybook/preset-create-react-app",
    '@storybook/preset-scss'
  ],
  webpackFinal: async (config, { configType }) => {
    config.module.rules.push({
      // this is for both less and scss
      test: /.*\.(?:le|c|sc)ss$/,
      loaders: [
        'style-loader',
        'css-loader',
        'less-loader', // if scss then add 'sass-loader'
      ]
    });
    config.plugins.push(new MiniCssExtractPlugin({
      filename: '[name]-[contenthash].css',
      chunkFilename: '[id]-[contenthash].css',
    }));
    return config;
  },
}

Here config is the object of existing storybook's webpack configuration. We are pushing the rules and plugins to this config object.

Step2:

In preview.js file include the below line

for less:
import '!style-loader!css-loader!less-loader!../YOUR_LESS_FILE.less';

for scss:
import '!style-loader!css-loader!sass-loader!../YOUR_LESS_FILE.scss';

That's it. Now you can run storybook and preview the changes :)

PS: I would like to thank Bastien for this reply on github thread.
https://github.com/storybookjs/storybook/issues/6364#issuecomment-485651328

Also I would like to thank @codevolution youtube channel for his awesome tutorials on storybook.
https://www.youtube.com/playlist?list=PLC3y8-rFHvwhC-j3x3t9la8-GQJGViDQk

💖 💪 🙅 🚩
mdrahiem
Rahimuddin

Posted on September 22, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related