iTranslated by AI
My Confusion After Accidentally Implementing CSS Modules Without Knowing It
I didn't even know CSS Modules existed. I had no idea.
(Even though I was the one who ran yarn add...)
TL;DR
- When running
yarn addor writing configuration files, make sure you properly understand what you are doing.- It's a shame, but it's common sense, isn't it?
- css-modules / postcss-modules | GitHub
The CSS transpiled by PostCSS looks strange
Before transpilation
body {
.dark {
background-color: #222;
}
}
After transpilation (Executed with Parcel + PostCSS)
body ._dark_57f73{background-color:#222}
What is this hash after the class name??????
It seems there is something called CSS Modules
I barely remember what keywords I used to find this, but it went something like this:
- It seems like something is enabled... (This turned out to be correct)
- Can I turn it off with Parcel CLI options...?
- Looking through various Parcel CLI options, trying them out
- Hmm, doesn't seem related...
- CLI | Parcel
- Is it a PostCSS setting...?
- Come to think of it, I specified
modules: true(copied it from somewhere), but what is this...? - Search for things like "Parcel css modules"
- Hit this site
- Why only CSS Modules has different settings in Parcel | nmm Laboratory Short
- Come to think of it, I specified
- What is CSS Modules!?
- → This is it!
- And it has nothing to do with
Parcel!!!
I think I arrived at the conclusion like that. Probably.
I see, so CSS Modules is something that automatically handles BEM-like (?) naming conventions.
- Implementing namespaces in CSS using CSS modules | Qiita
- Thoughts on CSS Modules | morishitter blog
- css-modules / postcss-modules | GitHub
Looking closely, the project's package.json where the issue was occurring had it properly installed:
"devDependencies": {
"postcss-modules": "^3.2.2",
}
I had enabled it in the Parcel .postcssrc configuration...
{
"modules": true, // ← Here
"plugins": {
"tailwindcss": {},
"postcss-nested": {},
}
}
Setting Naming Rules for CSS Modules
Since I'm here, let's try some additional configurations while keeping it enabled.
If you transpile with .postcssrc set like this:
{
"modules": true,
"plugins": {
"tailwindcss": {},
"postcss-nested": {},
"postcss-modules": {
"generateScopedName": "[name]__[local]",
}
}
}
application.css
body {
.dark {
background-color: #222;
}
}
This becomes:
application.css
body .application__dark{background-color:#222}
It turns out like this.
I see—how convenient!
Great, problem solved!
And since it's not needed for this project, yarn remove postcss-modules it is!! (Wait, what...)
Discussion