When using styled-components
in Next with React, it can become challenging to ensure that the styled components render correctly. To address this issue, Next supplies the compiler.styledComponents
flag
in next.config.js
as follows:
compiler: {
styledComponents: true
}
However, when this flag is enabled, it leads to the class names becoming unreadable as they increase in size exponentially.
The following images illustrate the difference in class names between when compiler.styledComponents
is disabled and when it is enabled.
When compiler.styledComponents
is not set:
When compiler.styledComponents
is set:
Is there a way to reduce the class name sizes to just their regular sc-XXXXXX
names?
I should note that we're not using the latest version of Next, but instead next@12.3.4
displayName
in babel-plugin-styled-components
Thanks to @vlad-vladov for pointing out the docs for this.
In the Next.js 12 and 13 docs for the Next.js compiler, it is stated that Next.js is using a port of babel-plugin-styled-components
and that the displayName
option is enabled by default in development and disabled in production. The documentation for babel-plugin-styled-components
states the following about the displayName
option:
This option enhances the attached CSS class name on each component with richer output to help identify your components in the DOM without React DevTools. In your page source you'll see:
<button class="Button-asdf123 asdf123" />
instead of just<button class="asdf123" />
.
To disable displayName
, just put false
:
module.exports = {
compiler: {
styledComponents: { displayName: false }
}
}
And to further explain why your class names were so long, the fileName
option (enabled by default) adds the name of the current file to the beginning of the displayName
when it's enabled.