Search code examples
javascriptreactjswebpackcreate-react-appstylus

How to configure Stylus support in a React.js application?


I want the classes in my React.js application to be available for export from .styl-files in the same way as it can be done from CSS Modules, but I can't find any ready-made solution to this problem.

I found a guide to setting up CSS Modules in an application created with Create React App.
I understand that you need to run npm run eject and somehow rewrite configuration files,
but how – I don't understand.


Solution

  • You need to install next npm-packages in your project:

    In webpack.config, in section module you need to add next points:

    {
      test: /\.styl$/,
      use: [
        'style-loader',
        'css-loader?modules&camelCase&localIdentName=[path]__[name]__[local]--[hash:base64:5]',
        'stylus-loader',
      ],
    },
    {
      test: /\.css$/,
      use: [
        'style-loader',
        'css-loader',
      ],
    },
    

    Then you can import your styles from .styl files in your React components like this:

    import style from './СomponentStyle.styl'; 
    

    and you can use style by CSS name for example:

    className={style.container} 
    

    where container - it is name of CSS but without dot. For complicated names like: .container-btn-green you need write next code: style.containerBtnGreen or style['container-btn-green']