Source originale du contenu
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.
It’s critical to recognise the massive shift that’s occurring here.
We can now make changes to our CSS with confidence that we’re not accidentally affecting elements elsewhere in the page. We’ve introduced a sane scoping model to our CSS.
The benefits of global CSS — style re-use between components via utility classes, etc. — are still achievable with this model. The key difference is that, just like when we work in other technologies, we need to explicitly import the classes that we depend on. Our code can’t make many, if any, assumptions about the global environment.
Writing maintainable CSS is now encouraged, not by careful adherence to a naming convention, but by style encapsulation during development.