Replies: 2 comments
-
|
This is an architectural challenge with how Tailwind generates CSS. The core issue: Tailwind tree-shakes by scanning source files for class names, not by analyzing runtime imports. It doesn't know which components the consumer actually uses — it just sees all class names in the content paths. Why your current approaches fail
The recommended approach: Don't bundle CSS in the libraryShip your components as JS/TSX only (no CSS bundle). Let the consumer's Tailwind process generate the CSS: /* Consumer's CSS file */
@import 'tailwindcss' prefix(sb);
@source "../node_modules/@stylibweb/stylib-components/src/**/*.{js,jsx,ts,tsx}";The key insight: both the library AND the consumer must use the same prefix. When the consumer configures
This way, only utilities used by the imported components end up in the final CSS — true tree-shaking. If you need the library to work standalone (with its own CSS)You're stuck with shipping the full CSS bundle. This is a fundamental limitation: Tailwind can't know at library-build-time which components the consumer will use. Mitigations:
On the prefix questionIf your library is the only thing using |
Beta Was this translation helpful? Give feedback.
-
|
It's may interest for you: |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Description
I'm developing a React component library that uses Tailwind CSS v4 (upgraded it from v3) with a custom prefix (
sb:). I'm facing a critical issue where tree-shaking doesn't work when using prefixed Tailwind utilities in component libraries.The Problem
When I build my component library with prefixed Tailwind utilities (e.g.,
sb:flex,sb:bg-blue-500), the generated CSS bundle includes all Tailwind utilities used across my entire library, not just the ones used in the components that consumers actually import.Example:
What I've Tried
1. Building with prefix in the library
Result: CSS bundle contains all utilities from entire library (not tree-shaken)
2. Adding library as content source in consumer's app
Result: Tailwind doesn't detect the prefixed classes (
sb:flex) because it's looking for unprefixed classes. The generated CSS doesn't include my library's styles.None of these approaches work correctly.
Current Workaround (Not Ideal)
My current solution is to export the entire CSS bundle:
This works but has significant downsides:
Questions
Is there a way to make Tailwind tree-shake prefixed utilities in component libraries?
Can I configure the consumer's Tailwind to detect prefixed classes from node_modules?
sb:*classes in this specific package"Should I avoid using prefixes in component libraries altogether?
Would a custom plugin or extractor help solve this?
Expected Behavior
I want to:
sb:) in my library components to avoid conflictsExample Use Case
thanks!!
Beta Was this translation helpful? Give feedback.
All reactions