Saturday 27 October 2018

The seemingly weird way in which styles are handled with CSS modules.

The first time I worked with code that used Webpack's CSS modules I didn't quite understand why it did what it did.

It turns out there is a reason why Webpack handles styles with CSS modules this way (...well obviously) and I learnt of it only recently.

For those of you who aren't familiar with what CSS modules is, here's the gist of it:

1. You write up your CSS.


2. Import your styles, inject it into your component.


3. Webpack then rewrites your class to look like this

post_postTitle_xb4ac

The class above consists of three parts separated by underscores. The first is the parent class, the second, the class added to the current component and the third is a hash.

So the question is why would we want to handle our CSS this way?

The answer...encapsulation.

The three parts mentioned above, combined, creates a class that won't conflict with other components. This means that when you write out your components in react and you add styles to them using CSS modules, the styles you apply to one element will be applied to only that element and won't spill over into another element.

This makes it easier to maintain your CSS when your application begins to grow in size. You won't have to worry about having to namespace your selectors to prevent styles from one component ending up on another.

The CSS modules technique is also probably a way of mimicking the style encapsulation that the shadow DOM provides by default. With the advent of web components and with the way frameworks that use web components use the shadow DOM you'll notice that this is becoming the preferred way of writing CSS (ie. having CSS scoped to its component).

It turns out all you need to work with CSS modules is a CSS module compiler. With Webpack this functionality is available and only needs to be enabled by way of configuration.

There seem to be other options too like this one here:
https://github.com/gajus/babel-plugin-react-css-modules.

Hope this post helped in some way.

No comments:

Post a Comment