Readable Classnames with Styled-Components
Please note that this articles purpose is to aid in debugging the dom tree when usuing styled-components, there are other alternatives to this technology that may suit your needs better however this is not a debate about which styling technique is the best.
Styled-components allow developers to write styles using CSS in JS via tagged template literals that work very well with tree shaking and in my opion makes code far more readable by keeping everythig in one file.
However one of the biggest issues that i have experianced with styled-components is when i inspect the dom tree the classnames are randomly genrated making it very hard to determine what the component source is.
There is however a very simple solution to this problem. By importing from `styled-components/macro` instead of `styled-components` and using babel you are able to get classnames that correlate to the styled component name.
This is great, we can now determine where our styles come from with ease but we probably don’t need this in production, so lets add a config that disables this helper in production builds.
First create a file called `babel-plugin-macros.config.js` and then add this content.
const isDev = process.env.NODE_ENV !== 'production';
module.exports = { styledComponents: { fileName: isDev, displayName: isDev }}
This will tell the babel plugin that for any build where the env is not production that readable display names can be created however if it is a production build then we don’t use the readable class names.
Hopefully this short article makes debugging a little easier for those of you that use styled-components, i highly recommend using the vscode plugin with this method for a great dev experiance.