I ran into a hard to debug issue today.
The production build of styled-components was failing by sharing a common CSS class for many styled components, but not in dev.
The issue was also fixed when switching to babel from SWC. But that turned out to be another false road.
I started a repo to try to reproduce the bug, but my patterns still failed to fail: https://github.com/department-nyc/next-swc-styled-components-bug/blob/main/next/components/example3.js
The bottom line is that every styled component was outputting a .styledComponentId
that was exactly the same, so the logic in the ID generator was somehow not working well with my particular setup. I know that it uses filepaths and all kinds of info to try to reliably identify components uniquely, so it’s just a black box to me.
Ultimately I found the solution in an undocumented option in the typescript typings: withConfig({displayName: <insert unique>}).
const Component = styled.div.withConfig({
displayName: styleName, // this was necessary to hint to styled components that these components are dynamic/different.
})<TypographyModifierProps>`
${handleReset}
${css_}
${typographyModifiers}
`
Now, I’m not sure why it works in the example. It may have to do with the monorepo structure or barrel files confusing the file paths. No idea, and not worth digging into. In today’s frontend world, you just have to compartmentalize some things as black boxes.
Bottom line: if you have issues with production styled component ID’s being wrong/the same, try logging the IDs first and see if styled-components is able to generate unique ones as expected. If it can’t, try to give it hints as to its uniqueness.
It looks like withConfig also supports a componentId
param to fully customize that internal id, but beware of using unsupported features.