The End of Global CSS

On April 22, 2015, Tobias Koppers — the ever tireless author of Webpack — committed the first iteration of a new feature to css-loader, at the time called placeholders, now known as local scope.

This feature allows us to export class names from our CSS into the consuming JavaScript code.

In short, instead of writing this:

require('./MyComponent.css');

We write this:

import styles from './MyComponent.css';

So, in this example, what does styles evaluate to?

To see what is exported from our CSS, let’s take a look at an example of what our style sheet might look like.

:local(.foo) {
color: red;
}
:local(.bar) {
color: blue;
}

In this case, we’ve used css-loader’s custom :local(.identifier) syntax to export two identifiers — foo and bar.

These identifiers map to class strings that we can use in our JavaScript file. For example, when using React:

import styles from './MyComponent.css';
import React, { Component } from 'react';
export default class MyComponent extends Component {
  render() {
return (
<div>
<div className={styles.foo}>Foo</div>
<div className={styles.bar}>Bar</div>
</div>
);
}
}

Importantly, these identifiers map to class strings that are guaranteed to be unique in a global context.

We no longer need to add lengthy prefixes to all of our selectors to simulate scoping. More components could define their own foo and bar identifiers which — unlike the traditional global selector model—wouldn’t produce any naming collisions.