CSS Modules in React TypeScript using Nx
Prerequisites
- Make sure you have installed Node.js version 16+.
- To follow along with this article, you’ll need a react project that is generated with Nx. If you haven’t done it yet, see this article.
You can still follow the article by creating components in your own way.
What is CSS Modules?
A CSS Module is a CSS file in which all class names and animation names are scoped locally by default. (see more)
Naming Convention
- CSS Modules files must be written in this format.
[filename].module.scss
Use appropriate file extension based on your stylesheet choice. For example,
app.module.css
,app.module.sass
orapp.module.scss
- CSS class names should be written in camelCase. But not mandatory.
.className {} // recommended
(or)
.class-name {}
Let’s Start
Open app.module.scss and write the following code.
And then, open app.tsx and write the following code.
There are two syntaxes to use CSS Module classes. You can use whatever you like but dot notation looks cleaner.
styles.container // recommended
(or)
styles['container']
Using Multiple CSS Modules classes
If you want to use multiple classes, you can use Template literals. For example, change the App component into this.
And put this code into app.module.scss file.
Serve the Application
Run with nx serve
and see the result.
Done
CSS Modules can reduce potential conflict between css classes. That’s why if your not using yet, give it a try.