28 tháng 2, 2026 · 9 phút đọc
Kiến trúc component với Tailwind CSS: tránh class string dài vô tận
Cách tổ chức Tailwind trong dự án lớn — variants, CVA, design tokens và khi nào nên extract ra component.
Tailwind CSS giải quyết vấn đề naming convention và specificity wars của CSS truyền thống. Nhưng khi codebase lớn, class strings dài 10-20 classes trên mỗi element trở thành vấn đề maintainability mới. Bài viết này chia sẻ các pattern thực tế.
Class Variance Authority (CVA)
CVA là thư viện giúp định nghĩa component variants một cách type-safe. Thay vì ternary chaos trong className, bạn định nghĩa base classes, variants và defaultVariants. shadcn/ui dùng CVA làm nền tảng — đây là pattern đáng học theo.
Ví dụ: một Button component với variants size (sm/md/lg) và intent (primary/secondary/danger). CVA generate type-safe props và merge classes đúng cách. Kết hợp với tailwind-merge để xử lý class conflicts khi extend.
Khi nào extract ra component?
Rule of thumb: extract khi (1) cùng class combination xuất hiện 3+ lần, (2) component có logic variants rõ ràng, (3) cần test isolate. Đừng extract quá sớm — premature abstraction khó refactor hơn duplication.
Tailwind Config là Design Token
tailwind.config.js là nơi định nghĩa design tokens của dự án. Extend theme với brand colors, custom spacing, fonts. Đặt tên semantic (brand-primary, text-muted) thay vì descriptive (blue-500) để dễ update khi design thay đổi.
Tailwind v4 và CSS-first config
Tailwind v4 dịch chuyển sang CSS-first configuration với @theme directive. Config nằm trong CSS file thay vì JS, syntax dùng CSS custom properties. Migration từ v3 cần cẩn thận nhưng benefits là PostCSS pipeline đơn giản hơn và performance build tốt hơn.