Micro-frontends: Fixing duplicate class name in Styled Component

Teno Siswono
2 min readJan 6, 2022

Having multiple micro frontends on your page can cause you some problems, one of them is class name pollution.

Each micro frontend is deployed to production independently (https://martinfowler.com/articles/micro-frontends.html)

If multiple micro frontend use styled-components, each instance of styled-components could generate the same class name hash. That is because styled-components generate class name hash based on the content of CSS ruleset you defined. So if the ruleset is similar there is the possibility to generate the same class name.

Solution 1: adding a prefix to styled-components

This babel plugin allows you to configure styled-components, one of their option is to add a namespace.

{
"plugins": [
["babel-plugin-styled-components", {
"namespace": "my-app"
}]
]
}

generate you:

<div class="my-app-fznNvL RiUPO">...</div>

but this solution still has some problems, we could still have an issue with the second generated class name `RiUPO`

Solution 2: wrap micro frontend to scope

css can be scoped by adding custom parent selector, and wrapping your micro app inside div with unique id

<div id="micro-1">
...
</div>
#micro-1 .classname

styled-components use stylis for CSS Preprocessor, lucky there is some plugin available in styles to add parent scope

Next, we add this stylish plugin into some provider

In our microfe we just need to wrap with this provider

with this styled will generated with scope

#micro-fe .RiUPO { ... }

--

--