How To Make Styled Components Class Names Readable

React

01/07/2021


As the class names of your styled components are generated, even attempting to debug them can be a nightmare. Fortunately, there is a way to make the names legible and more meaningful, for example from sc-AxgML to Header__StyledMainHeader-AxgML.

Add a plugin

If you're reading this article, you likely don't have the babel plugin installed - do so first.

BASH
npm install --save-dev babel-plugin-styled-components

In your .babelrc file, add the plugin.

JSON
{
"plugins": ["babel-plugin-styled-components"]
}

And there you go! 🥳 By default, the plugin will generate more legible class names by using your component's name and the name of the file it's in.

Additional configuration

You can exclude file names from the generated class names by configuring your .babelrc file accordingly.

JSON
{
"plugins": [
[
"babel-plugin-styled-components",
{
"fileName": false
}
]
]
}

However, if for whatever reason you wish to revert to unreadable 😛 class names, simple set displayName to false.

JSON
{
"plugins": [
[
"babel-plugin-styled-components",
{
"displayName": false
}
]
]
}

WRITTEN BY

Code and stuff