Everything you need to know about CSS modules

Everything you need to know about CSS modules

A CSS module is just a CSS file that gives you the possibility to style components. The most important advantage of CSS modules is that the styles are scoped locally by default, but what does this actually mean?

CSS is easy, right?

I started my web developer journey as a frontend developer, and with time I also started to deal with backend employees. My colleagues from the backend team were laughing that CSS is just a language for just setting margins and colors.

Keep in mind: if you do something more than adding color to headings…

CSS is not easy.

Take a look at the list below. The biggest CSS dangers are described here:

  1. Conflicts between CSS rules

  2. Overwrites

  3. A big CSS stylesheet with unused rules

  4. Side effects

CSS modules to the rescue

Thanks to the fact that CSS modules are scoped locally, the problems described above disappear.

  • no more conflicts

  • no side effects

  • no global scope

An example CSS module

Take a look below at a straightforward example of a CSS module in PWA Studio:

CSS module (this is just a CSS file)

1.section {
2    padding: 15px;
3}
4 
5.heading {
6    font-size: 24px;
7    font-weight: bold;
8    margin: 15px 0;
9}

The sample component which uses these styles:

1import React from "react";
2import classes from './sample-component.css';
3 
4const SampleComponent = () => {
5    return (
6        <div className={classes.section}>
7            <h3 className={classes.heading}>This is the sample component tilte</h3>
8            <p>This is the sample component paragraph</p>
9 
10            <h4 className={classes.heading}>This is the sample list:</h4>
11            <ul>
12                <li>Sample item A</li>
13                <li>Sample item B</li>
14                <li>Sample item C</li>
15            </ul>
16        </div>
17    )
18};
19 
20export default SampleComponent;

On the third line, we imported a CSS module called sample-component.css as a classes object. Now we are able to use classes from the CSS module as object properties. Take a look at lines 6,7, and 10.

So this is exactly what CSS modules do—they let you use CSS classes as object properties in JavaScript files.

How does it work?

Thanks to Webpack and the configuration of the loaders, the classes described in the CSS module, and applied in the React component, are rendered as unique CSS classes for each place where they are used.

CSS modules explanation
  1. Here is the place where the section class is applied to the node.

  2. This is a CSS rule which includes CSS properties.

  3. Here you can see a unique class name applied to the node in the compiled app.

  4. This is compiled into a unique CSS rule.

Webpack configuration

Take a look at the webpack configuration. In PWA Studio you can find them in @magento / pwa-buildpack / lib / WebpackTools / configureWebpack / getModuleRules.js file

1
2getModuleRules.css = async ({ paths, hasFlag }) => ({
3    test: /\.css$/,
4    oneOf: [
5        {
6            test: [paths.src, ...hasFlag('cssModules')],
7            use: [
8                'style-loader',
9                {
10                    loader: 'css-loader',
11                    options: {
12                        localIdentName: '[name]-[local]-[hash:base64:3]',
13                        modules: true
14                    }
15                }
16            ]
17        },
18        {
19            include: /node_modules/,
20            use: [
21                'style-loader',
22                {
23                    loader: 'css-loader',
24                    options: {
25                        modules: false
26                    }
27                }
28            ]
29        }
30    ]
31});

On line 11 you can see where the names of the compiled classes come from, and line 12 is where the CSS modules are enabled.

Composition

CSS modules let you compose rules from other rules:

1.heading {
2    font-size: 24px;
3    font-weight: bold;
4    margin: 15px 0;
5}
6 
7.secondaryHeading {
8    composes: heading;
9}

It’s possible to compose multiple selectors:

1.section {
2    padding: 15px;
3}
4 
5.header {
6    background-color: lightgray;
7}
8 
9.heading {
10    font-size: 24px;
11    font-weight: bold;
12    margin: 15px 0;
13}
14 
15.secondaryHeading {
16    composes: heading;
17}
18 
19.sampleHeader {
20    composes: section header heading;
21}

Global CSS Rules

Scoping styles locally is lovely, but sometimes you need to define some global CSS rules, for example for animations (keyframes). CSS modules let us create global rules using the :global() function.

1// global-styles.css
2:global(.global-class-name) {
3    color: red;
4}

When you import this CSS module into your app, you will be able to use a global CSS rule like this:

1// import stylesheet
2import './global-styles.css'
3...
4// example of using global CSS rule
5<p className="global-class-name">This is paragraph with global styles appiled</p>

Composing from global

Sometimes it is necessary to compose from a global rule to a local one, which you can do like this:

1.redHeading {
2    composes: global-class-name from global
3}

Naming conventions

It’s recommended to use the camel case naming convention because using classes in JS, in this case, is easiest. When the name of the class looks. for example, like this: .my-sample-class, then you can apply this class to an element in the following way:

1<ul className={classes['my-sample-class']}>

Merging and overrides classes

In PWA Studio you can pass classes as props to a component, and overwrite default component classes with classes from props. Take a look:

1import { mergeClasses } from '@magento/venia-ui/lib/classify';
2import defaultClasses from '@magento/venia-ui/lib/components/Main/main.css';
3 
4const Main = props => {
5   const classes = mergeClasses(defaultClasses, props.classes);
6}

If you pass classes as props, you can validate them using PropTypes:

1Main.propTypes = {
2    classes: shape({
3        page: string,
4        page_masked: string,
5        root: string,
6        root_masked: string
7    })
8};

Conclusion

In my opinion, locally scoped CSS resolve many problems and is a really nice, modern approach to managing styles. Perhaps for many Frontend Developers, this is a controversial approach, and that’s OK because this is completely different from what is commonly used.

Maybe you have experience with CSS modules? Let me know in the comments!

Thanks for reading. All likes, shares, and comments are really appreciated.

Github repository

You can find examples of the code for this article on my Github.Here is the repository.

Sources

https://magento.github.io/pwa-studio/technologies/basic-concepts/css-modules/

https://github.com/css-modules/css-modules

https://webpack.js.org/loaders/css-loader/#modules

https://x-team.com/blog/css-modules-a-new-way-to-css/

https://magento.github.io/pwa-studio/tutorials/pwa-studio-fundamentals/css-modules/

https://glenmaddern.com/articles/css-modules

About the author

Marcin Kwiatkowski

Certified Magento Full Stack Developer, based in Poland. He has 7 years of professional Software engineering experience. Privately, husband, father, and DIY enthusiast.

Read more