gotchacsstailwindMajor
@apply in component libraries causes specificity and purge issues
Viewed 0 times
@applycomponent librarypurgespecificitynpm packagestyles missing
Problem
Using @apply inside a CSS file to extract Tailwind utilities into component classes works locally but breaks in consumer apps: styles are purged because the CSS file is not scanned, or specificity conflicts arise.
Solution
For shared component libraries prefer one of two approaches:
Alternatively, pre-bundle the CSS and ship it separately:
- Ship unstyled components and let consumers apply classes directly.
- If you must use @apply, ensure the library's CSS file is included in the consumer's Tailwind content scan:
// Consumer's tailwind.config.js
module.exports = {
content: [
'./src/**/*.{js,ts,jsx,tsx}',
'./node_modules/@myorg/ui/dist/**/*.js', // scan the library
],
};Alternatively, pre-bundle the CSS and ship it separately:
/* In the library's own CSS build step */
@layer components {
.btn {
@apply px-4 py-2 rounded-md font-medium transition-colors;
}
}Why
@apply resolves at PostCSS compilation time. When a library is compiled independently, the consumer's purge pass has already happened and the resolved CSS is not re-evaluated against the consumer's content.
Gotchas
- @apply cannot reference utilities from a parent project's Tailwind config — the library must have its own Tailwind setup or ship plain CSS.
- Specificity: @apply-generated rules land in @layer components which has lower specificity than utilities — a consumer utility class will always win.
- In v4, @apply is still supported but the recommendation is to use CSS custom properties and @theme instead of component abstractions.
Context
When building a shared UI component library that uses Tailwind CSS internally.
Revisions (0)
No revisions yet.