Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Storybook default webpack config does not support CRA v2 w/ CSS modules #4306

Closed
matthamil opened this issue Oct 6, 2018 · 18 comments
Closed
Labels

Comments

@matthamil
Copy link

Bug or support request summary

From https://storybook.js.org/configurations/custom-webpack-config/:

The default Webpack config of Storybook is balanced for a medium-size project (specially created with Create React App) or a library.

I am assuming that this means that Storybook's default webpack config should be able to handle a new project created by CRA. CRA v2 now has opt-in support for CSS modules. When I created a new CRA project using CRA v2.0.4, I used CSS modules to style a component; however, the component styles do not appear when displaying the component in Storybook.

If this means that I need to extend Storybook's webpack config to add CSS module support, please close this issue. However, it's unclear if Storybook is meant to work out-of-the-box with CRA if this is the case. I can make a PR to add documentation around this if Storybook will not add CSS module support out of the box like CRA v2 has.

Steps to reproduce

I have a reproducible example in this repo.

  1. Create a project with npx create-react-app my-app
  2. Add Storybook to the project with getstorybook
  3. Create a component that imports a CSS module.
  4. Render the component in a Storybook story.

If you import the component that uses CSS modules into App.js and run yarn run start, you can see that the styles are applied correctly. However, if you run Storybook with yarn run storybook, the styles do not apply.

Please specify which version of Storybook and optionally any affected addons that you're running

package.json

{
  "name": "storybook-css-module",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.5.2",
    "react-dom": "^16.5.2",
    "react-scripts": "2.0.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "storybook": "start-storybook -p 9009 -s public",
    "build-storybook": "build-storybook -s public"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "devDependencies": {
    "@storybook/react": "^3.4.11",
    "@storybook/addon-actions": "^3.4.11",
    "@storybook/addon-links": "^3.4.11",
    "@storybook/addons": "^3.4.11",
    "babel-core": "^6.26.3",
    "babel-runtime": "^6.26.0"
  }
}

Affected platforms

Tested in Chrome v69

Screenshots / Screencast / Code Snippets (Optional)

Repo: https://github.com/matthamil/storybook-css-module-CRA2

Text component when running yarn run start:

image

Text component when running yarn run storybook:

image

Work summary

Add CSS module support to Storybook's webpack config.

Where to start

Take a look at ./src/Text.js and ./src/Text.module.css. The CSS module includes one class .text which applies a red color and 2rem font-size to whatever element is using .text.

Acceptance criteria

Default storybook webpack config can handle CSS modules out of the box.

Who to contact

anyone familiar with Storybook's default webpack config.

@matthamil matthamil changed the title Storybook default webpack config Storybook default webpack config does not support CRA v2 w/ CSS modules Oct 6, 2018
@matthamil
Copy link
Author

For anyone else who created a CRA v2 project that uses CSS modules, I extended the default webpack config by doing the following:

  1. create a webpack.config.js file in the .storybook directory
  2. Add the following CSS module rule:
// ./.storybook/webpack.config.js
const cssModuleRegex = /\.module\.css$/;

module.exports = {
  module: {
    rules: [
      {
        test: cssModuleRegex,
        loaders: [
          require.resolve('style-loader'),
          {
            loader: require.resolve('css-loader'),
            options: {
              importLoaders: 1,
              modules: true,
              localIdentName: '[name]__[local]___[hash:base64:5]'
            }
          }
        ]
      }
    ]
  }
};

Now CSS modules should work for your CRA + Storybook project.

@igor-dv
Copy link
Member

igor-dv commented Oct 7, 2018

If we are talking about compatibility with CRA2, I think we need to support as much as possible by default. For example, in @storybook/angular, we do recognize that there is a usage of angular-cli and we try to use its configuration as much as possible.
So extending the custom webpack.config.js is kinda workaround.

Do you want to PR the better CRA2 compatibility for css modules?

@chadfawcett
Copy link
Member

@igor-dv I can take this on. Depending how it goes, I may be able to take on #4298 as well.

Just a quick question, would you want me to update examples/cra-kitchen-sink to react-scripts@^2.0.0 as part of this PR?

@igor-dv
Copy link
Member

igor-dv commented Oct 10, 2018

I can take this on

That will be cool 👍

would you want me to update examples/cra-kitchen-sink to react-scripts@^2.0.0

I would say yes

@markreid
Copy link

markreid commented Oct 11, 2018

Thanks for the snippet @matthamil

For anybody who wants to use SCSS modules, you can modify it slightly to use:

const sassModuleRegex = /\.module\.(scss|sass)$/;

module.exports = {
  module: {
    rules: [
      {
        test: sassModuleRegex,
        loaders: [
          require.resolve('style-loader'),
          {
            loader: require.resolve('css-loader'),
            options: {
              importLoaders: 2,
              modules: true,
              localIdentName: '[name]__[local]___[hash:base64:5]'
            }
          },
          require.resolve('sass-loader'),
        ]
      }
    ]
  }
};

@ndelangen
Copy link
Member

@chadfawcett please join our discord: https://discord.gg/sMFvFsG

So we can help you faster.

@ndelangen
Copy link
Member

ndelangen commented Oct 12, 2018

@igor-dv @chadfawcett and I discussed and he's on board what we think should be done.

We could use your advice and expertise about presets!
We came up with the idea of creating a CRA2 preset.

  • what do you think of that idea?
  • where should such a bit of code exist?
  • how do we use it? will it be added for all apps with react? or can we filter for CRA only?

@igor-dv
Copy link
Member

igor-dv commented Oct 12, 2018

I like the preset idea. The similar preset for angular is located in @storybook/angular. It detects that we are using angular-cli and changes things accordingly. If we can make the same for react, that'd be great. At least while the "custom" presets are not publicly exposed.

How can we detect that somebody is using cra ?

@chadfawcett
Copy link
Member

chadfawcett commented Oct 12, 2018

@igor-dv Since the webpack used to be solely based on CRA's webpack config, would it be okay to just narrow down that scope to apply to all @storybook/react setups? Therefore just adding the preset in app/react/src/server/ without doing any checks?

Alternatively we could do something similar to the angular check and load a file, like package.json, and check for the presence of react-scripts as a dependency?

What are your thoughts?

Edit: The react options.js does imply that it's create-react-app https://github.com/storybooks/storybook/blob/116904073ae847726afada56c1aa6f12e3ecffe3/app/react/src/server/options.js#L5

@robcaldecottvelo
Copy link
Contributor

Similarly, the new <> React Fragment syntax is not supported.

@ndelangen
Copy link
Member

@robcaldecottvelo You've tried the alpha? I thought the fragment syntax should be supported there.

We're releasing 4.0.0 rc today

@weyert
Copy link
Contributor

weyert commented Oct 15, 2018

Hello, I am trying out the latest version of storybook (4.0.0-rc.0) and I was wondering if the sass and css modules support should work out of the box or do I need to do something special? I am getting the error:

ERROR in ./src/BulmaTheme.scss 1:0
Module parse failed: Unexpected character '@' (1:0)
You may need an appropriate loader to handle this file type.
> @import '~bulma/sass/utilities/initial-variables.sass';
|
| // ADD HERE variables you want to override
 @ ./src/common-ui/components/orders/EditOrderForm.js 9:0-34
 @ ./src/common-ui/components/orders/EditOrderForm.story.js
 @ ./src/common-ui sync \.story\.js$
 @ ./.storybook/config.js
 @ multi ./node_modules/@storybook/core/dist/server/config/polyfills.js ./node_modules/@storybook/core/dist/server/config/globals.js ./.storybook/config.js ./node_modules/webpack-hot-middleware/client.js?reload=true

Looks like the following custom webpack resolves the problem:

module.exports = (storybookBaseConfig, configType, defaultConfig) => {
    defaultConfig.module.rules.push({
        test: /\.s[ca]ss$/,
        use: [require.resolve('style-loader'), require.resolve('css-loader'), require.resolve('sass-loader')]
    })

    return defaultConfig
  }

Maybe it only supports the extension scss and not sass?

@weyert
Copy link
Contributor

weyert commented Oct 15, 2018

Hmm, now it complains about babel-loader missing but yarn add babel-loader --dev seems to fix it for now. Let's see for how long :)

@matthamil
Copy link
Author

@weyert you'll need to do something special for now. Per the conversation earlier in this thread, it was decided that compatibility with CRA2 (which includes support for sass & css modules out of the box) will be included in the future.

@weyert
Copy link
Contributor

weyert commented Oct 15, 2018

Sorry, somehow I thought it was included as part of today's release!

@chadfawcett
Copy link
Member

@weyert Further discussion can be found on the PR #4405

@shilman shilman added the cra Prioritize create-react-app compatibility label Nov 22, 2018
@jnhooper
Copy link

jnhooper commented Feb 14, 2019

for anyone else who comes across this I had issues with sass-loader not liking being used twice, so i came up with this solution

module.exports = (BaseConfig, env, defaultConfig) => {
  const rules = [];
  // Do this because sass-loader does not like it when there are
  // multiple declarations of it in rules.. and we want css modules
  // turned on
  defaultConfig.module.rules.forEach(rule => {
    const testCssString = "myscss.scss";
    const regex = RegExp(rule.test);
    if(!regex.test(testCssString)){
      rules.push(rule);
    }
  });
  defaultConfig.module.rules = rules;

  defaultConfig.module.rules = [
    {
      test: /\.scss$/,
      include: srcDir,
      loaders: [
        "style-loader",
        {
          loader: "css-loader",
          options: {
            importLoaders: "1",
            localIdentName: "[name]__[local]___[hash:base64:5]",
            modules: true,
          }
        },
        "sass-loader"
      ]
  },
      {
        test: /\.svg$/,
        issuer: {
          test: /.jsx?$/
        },
        use: ['@svgr/webpack']
      },
  ...rules
  ]

@MrJadaml
Copy link

MrJadaml commented Aug 3, 2019

This is how I ended up getting css modules to work

// .storybook/webpack.config.js

const setCssModulesRule = rule => {
  const nextRule = rule;
  const cssLoader = rule.use[1];  // admittedly lazy, but the array was mixed types 🤷‍♀️
  const nextOptions = { ...cssLoader.options, modules: true }

  cssLoader.options = nextOptions;  
  return nextRule;
}

module.exports = async ({ config, mode }) => {
  const rules = config.module.rules.map(rule => {
    const isCssRule = rule.test.toString().indexOf('css') !== -1;
    let nextRule = rule;

    if (isCssRule) {
      nextRule = setCssModulesRule(rule);
    }

    return nextRule;
  });

  config.module.rules = rules;
  return config;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

10 participants