Hacker News new | ask | show | jobs
by lisper 3558 days ago
> CSS Modules is still a "naming convention," just one that is auto-generated for you.

Yes, that's true, but your use of the word "just" implies that auto-generation is a detail. It's not. It's the the big win. At root, everything is machine code, which also has a flat namespace. Having that flat-namespace code auto-generated is a huge lever.

1 comments

And it fixes a few other unexpected problems as well.

We use SHA1 hashes of the CSS classes' contents as it's name when using CSS modules. This has the cool side effect of making any 2 classes that do the same thing to have the same name, and get de-duped in the final output, regardless of where they originated in the application.

When I saw it happen the first time, it really kind of cemented in the idea that this combined with a way to "punch through" the modularity to combine and extend "base" classes and include global colors (for us it's SASS imports) has pretty much "solved" CSS for me.

That's a nice trick -- thanks for sharing! Am I write in understanding that implementing this within webpack is simply using only [hash] as the localIdent configuration property for css-loader?
yeah, specifically [hash:base64] because [hash] will print the hex of the hash which is a bit more verbose. I think it's actually the default for css-loader if you don't set localIdentName

During development we have it set to `[local]---[path]---[name]---[hash:base64:5]` which gives massive verbose class names but lets me pinpoint exactly where they came from.

There's also one step that I left out that helps, which is to have something like csscomb[0] to order the properties of each class into a set order. It really lets this optimization shine by ensuring that different property-order won't cause different hashes.

[0] https://github.com/csscomb/csscomb.js

Neat trick, but SHA1 is serious overkill for this. Even MD5 would be overkill. You don't need a cryptographically secure hash if you aren't dealing with inputs controlled by an adversary.
Yeah it's overkill, but it ads basically no extra time to our build, so there's no need to optimize it.