Can I use CSS Modules with Storybook 5 (React flavour)?

Saldog picture Saldog · Mar 12, 2019 · Viewed 7.4k times · Source

I am trying to use Storybook v5.0 with my project and I am using React + Webpack4 + CSS Modules. ( I am not using CreateReactApp)

My setup is quite simple, and I was able to setup Storybook without CSS modules fine.

However if I try to edit the custom storybook webpack config to support CSS modules, it errors.

When I run npm run storybook the error I get is:

ERROR in ./src/components/Test/index.css (./node_modules/css-loader/dist/cjs.js??ref--6-1!./node_modules/postcss-loader/src??postcss!./node_modules/style-loader!./node_modules/css-loader/dist/cjs.js??ref--9-1!./node_modules/postcss-loader/src!./src/components/Test/index.css)
Module build failed (from ./node_modules/postcss-loader/src/index.js):
SyntaxError

(2:1) Unknown word

  1 |
> 2 | var content = require("!!../../../node_modules/css-loader/dist/cjs.js??ref--9-1!../../../node_modules/postcss-loader/src/index.js!./index.css");
    | ^
  3 |
  4 | if(typeof content === 'string') content = [[module.id, content, '']];

In my package.json:

"@storybook/addon-actions": "^5.0.0",
"@storybook/addons": "^5.0.0",
"@storybook/react": "^5.0.0",

My .storybook/webpack.config.js follows the example on their web site, and looks like this:

const path = require("path");

const stylesLoaders = [
  "style-loader",
  {
    loader: "css-loader",
    options: {
      modules: true,
      localIdentName: "[path]__[local]--[hash:base64:5]"
    }
  },
  "postcss-loader"
];

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        loaders: stylesLoaders,
        include: path.resolve(__dirname, "../")
      }
    ]
  }
};

Any help would be appreciated, as I'd like to use the latest version of Storybook!

Answer

Aakash picture Aakash · Sep 27, 2020

This is what worked for me:

// ./.storybook/main.js
module.exports = {
  //
  webpackFinal: (config, {configType}) => {
    const path  = require('path');

    config.module.rules.push({
      test: /\.css$/,
      use: ['style-loader', 'css-loader?modules=true'],
      include: path.resolve(__dirname, '../'),
    });
    
    return config;
  }
  //
}

AND

Renaming my CSS files from <filename>.css to <filename>.module.css.

Good Luck...