reactjswebpackcss-modules

How to use global variables in CSS-Modules?


I'm busy learning React with CSS-Modules and I don't quite understand how one would store variables? For example, in Sass you're able to do this:

// _variables.scss
$primary-color: #f1f1f1; 

// heading.scss
@import './variables';
.heading {
  color: $primary-color
}

How do you achieve this in CSS Modules?


Solution

  • One way could be to use dependencies. For example,

    // variables.css
    .primaryColor {
      color: #f1f1f1
    }
    
    // heading.css
    .heading {
      composes: primaryColor from "./variables.css"
    }
    

    See more detailed information here: https://github.com/css-modules/css-modules#dependencies

    If you're using webpack there are more examples here: https://github.com/webpack/css-loader#composing-css-classes

    Also if you are using webpack you can still use Sass with CSS modules.