I created a React component library using mantine with @rollup package. This library comprises custom components styled with styled-components and CSS module (.module.css) files.
All the css modules are bundled in javascript and injected into the body html element: Inject css
The library is packaged in esm
, cjs
, and umd
.
The css is generated using the rollup plugin: rollup-plugin-styles
:
styles({
modules: true,
autoModules: true,
mode: [
"inject",
{ container: "body", singleTag: true, prepend: true, attributes: { id: "global" } },
],
})
An issue I am facing is that the class names utilized in my components get altered by next.js during server-side preprocessing before being sent to the client. For instance: In my esm module file:
var css = ".Layout_module_container__61ae088e {\n display: flex;\n flex-direction: column;\n height: 100vh;\n}\n.Layout_module_main__61ae088e {\n display: flex;\n flex-direction: column;\n flex-grow: 1;\n overflow-y: auto;\n padding: 0 1.5rem;\n}";
var modules_e616121b = {"container":"Layout_module_container__61ae088e","main":"Layout_module_main__61ae088e"};
n(css,{"container":"body","singleTag":true,"prepend":true,"attributes":{"id":"global"}});
In the js loaded stylesheet (in body html):
<body>
<style type="text/css" id="global">
@media (min-width: 36rem) {.Footer_module_container__fe0fb20d {
padding: var(--mantine-spacing-md)
}
}
@media (max-width: 36rem) {.Footer_module_container__fe0fb20d {
padding: var(--mantine-spacing-xs)
}
}
.Footer_module_infosContainer__fe0fb20d {
flex-direction: column;
flex-grow: 1;
align-items: start;
}
@media (min-width: 768px){
...
</style>
</body>
The correct class name should be displayed here: div
<div style="gap:var(--mantine-spacing-md);align-items:center;justify-content:space-around" class="m-8bffd616 mantine-Flex-root __m__-R1d5bsm"/>
The classname gets changed in the html to something like: __m__*
but remains the same in the stylesheet.
A similar issue occurs with styled-components
as well.
styled-component error
next-dev.js:20 Warning: Prop `className` did not match. Server: "m-8a5d1357 mantine-Title-root" Client: "WebsiteSelector_module_websiteName__547dd6e4 m-8a5d1357 mantine-Title-root"
I have tried multiple solutions found online, but none seem to work for me. These include:
- Removing css injection in js and creating a separate css file imported in App.tsx on next.js
- Adding babel-plugin-styled-components plugins in babel.rc file. However, this led to disabling swc to enable babel (resulting in performance loss)
The library works perfectly fine with vite.js, indicating that the issue lies solely on the next.js side.
Versions of my app:
dependencies: {
"next": "12.3.4",
"react": "18.2.0",
"react-dom": "18.2.0",
}
Version of my library:
"dependencies": {
"react": "18.2.0",
"react-dom": "18.2.0",
},
"devDependencies":{
"react": "^18.2.0",
"react-dom": "^18.2.0",
"styled-components": "^6.1.8"
}
Any help would be greatly appreciated 🙏🏻.