Tailwind v3 in a package #18679
Replies: 3 comments
-
|
try wrapping all your tailwind imports inside a shadow dom.. let me know if it work |
Beta Was this translation helpful? Give feedback.
-
|
Hello! This CSS leakage issue is common when building component libraries with Tailwind. Here are the recommended solutions: Solution 1: CSS-in-JS with Scoped Styles import { styled } from '@stitches/react';
const StyledButton = styled('button', {
backgroundColor: 'var(--primary-color)',
padding: '0.5rem 1rem',
});
export const Button = ({ children }) => {
return <StyledButton>{children}</StyledButton>;
};Solution 2: Tailwind CSS Layer Scoping @tailwind base;
@tailwind components;
@tailwind utilities;
@layer components {
.btn-primary {
@apply bg-blue-500 text-white px-4 py-2 rounded;
}
.card {
@apply bg-white shadow-lg rounded-lg p-6;
}
}Solution 3: CSS Modules Approach import styles from './Button.module.css';
export const Button = ({ children }) => {
return <button className={styles.primary}>{children}</button>;
};.primary {
@apply bg-blue-500 text-white px-4 py-2 rounded;
}Solution 4: Build-Time Class Name Hashing module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: {
localIdentName: '[name]__[local]--[hash:base64:5]',
},
},
},
'postcss-loader',
],
},
],
},
};Solution 5: Shadow DOM for Complete Isolation class MyComponent extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
/* Your scoped Tailwind styles */
.btn { /* ... */ }
</style>
<button class="btn">Click me</button>
`;
}
}The CSS Modules approach (Solution 3) is typically the most practical for React component libraries, as it provides automatic scoping without runtime overhead. |
Beta Was this translation helpful? Give feedback.
-
|
Thanks a lot guys. I'll try with layers |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello everyone, I need some help.
I've created a package and used Tailwind v3 for styling. Everything works fine, but there’s an issue with CSS custom properties. When my package is imported, these CSS custom properties "leak" into the application that uses my package. As a result, every element in the host application gets these custom properties, which is messy, hurts performance, and is just inconvenient.
Is there any way to avoid this?

Beta Was this translation helpful? Give feedback.
All reactions