A place to cache linked articles (think custom and personal wayback machine)
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

index.md 17KB

title: The End of Global CSS url: https://medium.com/seek-ui-engineering/the-end-of-global-css-90d2a4a06284 hash_url: 95e919fd9d

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.

As a result of this scoping model, we’ve handed control of the actual class names over to Webpack. Luckily, this is something that we can configure.

By default, css-loader transforms our identifiers into hashes.

For example, this:

:local(.foo) { … }

Is compiled into this:

._1rJwx92-gmbvaLiDdzgXiJ { … }

In development, this isn’t terribly helpful for debugging purposes. To make the classes more useful, we can configure the class format in our Webpack config as a parameter to css-loader:

loaders: [
...
{
test: /\.css$/,
loader: 'css?localIdentName=[name]__[local]___[hash:base64:5]'
}
]

In this case, our foo class identifier from earlier would compile into this:

.MyComponent__foo___1rJwx { … }

We can now clearly see the name of the identifier, as well as the component that it came from.

Using the node_env environment variable, we can configure different class patterns for development and production.

loader: 'css?localIdentName=' + (
process.env.NODE_ENV === 'development' ?
'[name]__[local]___[hash:base64:5]
' :
'[hash:base64:5]'
)
Now that Webpack has control of our class names, we can trivially
add support for minified classes in production.

As soon as we discovered this feature, we didn’t hesitate to localise the styles in our most recent project. We were already scoping our CSS to each component with BEM — if only by convention — so it was a natural fit.

Interestingly, a pattern quickly emerged. Most of our CSS files contained nothing but local identifiers:

:local(.backdrop) { … }
:local(.root_isCollapsed .backdrop) { … }
:local(.field) { … }
:local(.field):focus { … }
etc…

Global selectors were only required in a few places in the application. This instinctively led towards a very important question.

What if — instead of requiring a special syntax — our selectors were local by default, and global selectors were the opt-in exception?

What if we could write this instead?

.backdrop { … }
.root_isCollapsed .backdrop { … }
.field { … }
.field:focus { … }

While these selectors would normally be too vague, transforming them into css-loader’s local scope format would eliminate this issue and ensure they remain scoped to the module in which they were used.

For those few cases where we couldn’t avoid global styles, we could explicitly mark them with a special :global syntax.

For example, when styling the un-scoped classes generated by ReactCSSTransitionGroup:

.panel :global .transition-active-enter { … }

In this case, we’re not just scoping the local panel identifier to our module — we’re also styling a global class that is outside of our control.


Once we started investigating how me might implement this local-by-default class syntax, we realised that it wouldn’t be too difficult.

To achieve this, we leveraged PostCSS — a fantastic tool that allows you to write custom CSS transformers as plugins. One of the most popular CSS build tools today — Autoprefixer — is actually a PostCSS plugin that doubles as a standalone tool.

To formalise the usage of local CSS, I’ve open sourced a highly
experimental plugin for PostCSS called
postcss-local-scope. It’s still under heavy development, so use it in production at your own risk.

If you’re using Webpack, it’s a relatively straightforward process to hook postcss-loader and postcss-local-scope up to your CSS build process. Rather than document it here, I’ve created an example repository — postcss-local-scope-example—that shows a small working example.


Excitingly, introducing local scope is really just the beginning.

Letting the build tool handle the generation of class names has some potentially huge implications. In the long term, we could decide to stop being human compilers and let the computer optimise the output.

In the future, we could start generating shared classes between components automatically, treating style re-use as an optimisation at compile time.

Once you’ve tried working with local CSS, there’s really no going back. Experiencing true local scope in our style sheets — in a way that works across all browsers— is not something to be easily ignored.

Introducing local scope has had a significant ripple effect on how we approach our CSS. Naming conventions, patterns of re-use, and the potential extraction of styles into separate packages are all directly affected by this shift, and we’re only at the beginning of this new era of local CSS.

Understanding the ramifications of this shift is something that we’re still working through. With your valuable input and experimentation, I’m hoping that this is a conversation we can have together as a larger community.

To get involved, make sure you see it with your own eyes by
checking out postcss-local-scope-example.

Once you’ve seen it in action, I think you’ll agree that it’s not just hyperbole — the days of global CSS are coming to an end. The future of CSS is local.


Note: Automatically optimising style re-use between components would be an amazing step forward, but it definitely requires help from people a lot smarter than me. Hopefully, that’s where you come in ☺