reduce styled-component className length in next
Asked Answered
V

1

6

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:

before

When compiler.styledComponents is set:

after

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 [email protected]

Vidovik answered 17/4, 2023 at 10:37 Comment(1)
have you experimented with displayName and fileName options in next.config.js? See nextjs.org/docs/advanced-features/compiler#styled-componentsAho
A
6

Disable 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.

Amaryllis answered 21/4, 2023 at 17:57 Comment(1)
Perfect – thank you! Although, I opted to keep the displayName property enabled and just disabled fileName. :-)Vidovik

© 2022 - 2024 — McMap. All rights reserved.