- /
- Gatsby/
- How to Use CSS Module in Gatsby JS
In this tutorial, we will be discussing what is CSS Module, why and how to use it and finally, we will be implementing CSS Module using Gatsby.
What is CSS Module?
For those who are not familiar to CSS Module, the easiest way I can describe it is you write a css code and you access it like a Javascript Object. This means that if it is an object, you can import it and use dot or bracket to access the object property name.
objectName.propertyName or objectName['propertyName']
But this is not actually a css file which the browser can read. It is like a build process that transform it to a browser readable file using Open webpackwebpack or Open browserifybrowserify.
Why use CSS Module?
The best use of CSS Module is no more class name clashes since all classes/selectors will have unique names. Did you ever experience writing css classes and then you're conscious if that class name is already existing?
In some cases you will accidentally add a style to the one which is already working fine. This class name issues can make side effects specially if you are working in a large project. So CSS module will fix this issue by transforming your classes with unique class names.
CSS Module is also applicable to only one component where it was imported. This is good since Gatsby is a react-based framework, we can take advantage of its modularity. One good example if you have different components like button, checkbox, etc., you can add their own styles without worrying selector names. You can use the same class name to every component.
Lastly, no more long class names like Open BEM methodologyBEM methodology. A simple class name will work.
How to use CSS Module?
To use CSS module using Gatsby, first you need to create a new file with module.css file name. Say for example, we have a component layout.js, we can create a new file layout.module.css.
Under layout.js, you need to import layout.module.css. Notice below that the class name will be added like a javascript object and class name with dash will be converted using camel case.
Create and Implement CSS Module?
To better understand how to implement CSS module using Gatsby, kindly check the video below.
Read next article
How to Use SCSS or SASS in Gatsby JS