Global SCSS using CSS Modules in React (Gatsby)

I am trying to use some SCSS variables/fonts in a Gatsby project which uses CSS modules. Currently my project structure looks like this:

├── components
        ├── Footer
                ├── footer.module.scss
                ├── index.js
        ├── Header
                ├── header.module.scss
                ├── index.js
        ├── Layout.js
                ├── layout.module.scss
├── pages
        ├── index.js
├── styles
        ├── _typography.module.scss
        ├── _variables.module.scss

Gatsby’s docs recommend putting global styles into a Layout component (containing the header & footer) and then wrapping this around all other components. This works fine for the styles contained within the layout.module.scss file, but if I import the _variables.module.scss into this file, then I cannot use the variables in other SCSS files (for example header.module.scss).

What is the best way to structure my application so that I can access global variables/fonts in my modules? Do I just need to import the partial files into all of the individual modules when needed?

Thank you!


You have multiple approaches. I think the best and straightforward approach is importing the partial files (variables, functions, mixins, etc) into each individual module when needed since it would be a dependency of that specific file (it makes structural sense).

If your system and modules are properly structured, webpack will tree shake your SCSS modules and will remove the dead-code so you don’t need to worry about importing the same file (let’s say _variables.module.scss) into each specific module.