Can't get Storybook to work with CSS Modules using SCSS
  • 23-May-2023
Lightrun Team
Author Lightrun Team
Share
Can't get Storybook to work with CSS Modules using SCSS

Can’t get Storybook to work with CSS Modules using SCSS

Lightrun Team
Lightrun Team
23-May-2023

Explanation of the problem

 

There is an issue I’m facing while using Storybook with my React.js project that involves CSS Modules with SCSS. The problem arises when running Storybook with the provided configuration. Below are the relevant code snippets from the webpack.copy.js and main.js files.

The webpack.copy.js file, which is working correctly for “npm start,” is as follows:

 

const paths = require("../../paths");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { presets, plugins } = require("./webpack.config.babel");

module.exports = {
  // Configuration properties
};

 

On the other hand, the main.js file for Storybook seems to have an incorrect configuration that results in missing CSS styles for the components:

 

const path = require("path");

module.exports = {
  addons: [
    // Addon configuration
  ],

  stories: ["../src/**/*.stories.[tj]s"],

  webpackFinal: async (config, { configType }) => {
    // Webpack configuration modifications
  },
};

 

Upon running “npm run storybook,” the Storybook browser window opens, but the components are not styled with CSS. This issue indicates that the configuration in the main.js file might be incorrect. Assistance in resolving this problem would be highly appreciated.


Troubleshooting with the Lightrun Developer Observability Platform

 

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.

  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

Start for free today

Problem solution for: Can’t get Storybook to work with CSS Modules using SCSS

 

To address the issue of missing CSS styles in Storybook when using CSS Modules with SCSS, you can make the following adjustments to the Storybook main.js configuration:

 

const path = require("path");

module.exports = {
  addons: [
    // Addon configuration
  ],

  stories: ["../src/**/*.stories.[tj]s"],

  webpackFinal: async (config, { configType }) => {
    // Find the CSS rule index
    const ruleCssIndex = config.module.rules.findIndex(
      (rule) => rule.test.toString() === "/\\.css$/"
    );

    // Set the 'module' option to true for CSS rule loaders
    config.module.rules[ruleCssIndex].use.map((item) => {
      if (item.loader && item.loader.includes("/css-loader/")) {
        item.options.modules = {
          mode: "local",
          localIdentName:
            configType === "PRODUCTION"
              ? "[local]__[hash:base64:5]"
              : "[name]__[local]__[hash:base64:5]",
        };
      }

      return item;
    });

    // Add a new rule for SCSS files
    config.module.rules.push({
      test: /\.scss$/,
      use: ["style-loader", "css-loader", "sass-loader"],
      include: path.resolve(__dirname, "../"),
    });

    return config;
  },
};

 

By modifying the webpackFinal function in the main.js file, this solution updates the CSS rule to support CSS Modules and adds a new rule for handling SCSS files. Make sure to include the necessary loaders (style-loader, css-loader, and sass-loader) and specify the appropriate paths and configurations for your project.

These adjustments should enable Storybook to correctly apply CSS styles to your components when using CSS Modules with SCSS.

 

Problems with storybook

 

Issue: Storybook does not display components or stories.

  • Problem Description: When running Storybook, the browser window opens, but no components or stories are displayed.
  • Solution: One possible cause for this issue is incorrect configuration or missing story files. Ensure that the stories are properly defined and located in the specified directory. Additionally, check the Storybook configuration file (e.g., .storybook/main.js) to ensure that the stories are correctly referenced. Here’s an example of a correct Storybook configuration:

 

module.exports = {
  stories: ["../src/**/*.stories.js"],
};

 

Issue: CSS styles are not applied to components in Storybook.

  • Problem Description: Components displayed in Storybook lack CSS styles, causing them to appear unstyled or incorrectly rendered.
  • Solution: This problem may occur due to improper configuration of CSS loaders or missing loaders for specific file types. Verify that the correct loaders are installed and configured in the webpack configuration for Storybook. Here’s an example configuration that includes the necessary loaders for CSS and SCSS files:

 

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.scss$/,
        use: ["style-loader", "css-loader", "sass-loader"],
      },
    ],
  },
};

 

Issue: Storybook fails to load external dependencies or assets.

  • Problem Description: Components or stories that rely on external dependencies or assets (such as images or fonts) do not render correctly in Storybook.
  • Solution: To ensure that Storybook can load external dependencies and assets, proper webpack configuration is required. Verify that the necessary loaders are set up to handle the specific file types, and ensure that the file paths and import statements in your components are accurate. Here’s an example configuration for loading images with the file-loader:

 

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: "file-loader",
            options: {
              name: "[name].[ext]",
              outputPath: "images/",
            },
          },
        ],
      },
    ],
  },
};

 

A brief introduction to storybook

 

Storybook is a powerful tool for developing and testing UI components in isolation. It provides a dedicated environment where developers can showcase, interact with, and document their components.

At its core, Storybook enables the creation of “stories” that represent different states or variations of a component. These stories are written using popular JavaScript frameworks, such as React, Angular, or Vue, and can include both code and documentation. By organizing stories into a hierarchical structure, developers can effectively navigate and explore the components in a systematic manner.

One of the key benefits of Storybook is its ability to isolate components from the larger application context. This isolation allows developers to focus on the individual components, test different scenarios, and iterate rapidly. Storybook provides a live reloading development environment, making it easy to visualize and interact with components in real-time. It also offers a range of addons and integrations, such as component controls, accessibility testing, and visual regression testing, further enhancing the development and testing process.

In summary, Storybook serves as a central hub for component-driven development, offering a dedicated space to develop, showcase, and document UI components in isolation. Its intuitive interface, live reloading capability, and extensive addon ecosystem make it a popular choice among developers for building and maintaining robust component libraries.

 

Most popular use cases for storybook

 

  1. Component Development and Testing: Storybook allows developers to build and test UI components in isolation. It provides a platform to create and showcase different variations of components, making it easier to develop and fine-tune their behavior and appearance. Developers can define stories that represent specific states or use cases of a component, enabling comprehensive testing and ensuring the components work as expected. Here’s an example of defining a story for a React component using Storybook:

 

// Button.stories.js
import React from 'react';
import Button from './Button';

export default {
  title: 'Components/Button',
  component: Button,
};

export const Primary = () => <Button variant="primary">Primary Button</Button>;
export const Secondary = () => <Button variant="secondary">Secondary Button</Button>;
export const Disabled = () => <Button disabled>Disabled Button</Button>;

 

  1. Documentation and Collaboration: Storybook serves as a documentation tool for UI components. Developers can write detailed documentation alongside the component stories, explaining the purpose, usage, and available props of each component. This helps in maintaining a centralized and up-to-date documentation resource for the development team and other stakeholders. Storybook’s interactive interface makes it easier to visualize and understand component behaviors, facilitating collaboration among designers, developers, and product owners.
  2. Design System and Style Guide: Storybook is an excellent tool for building and maintaining design systems and style guides. By defining a library of reusable components with consistent styles and behaviors, developers can enforce design guidelines across projects. Storybook allows the creation of a visual reference for the design system, showcasing the available components, their variations, and usage guidelines. This enables teams to ensure design consistency, promote reusability, and streamline the development process by providing a centralized resource for designers and developers to refer to.
Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.