Bỏ qua đến nội dung
← Tất cả tips
1 phút đọc
  • #tailwind
  • #css
  • #patterns

Khi nào dùng `@apply` (và khi nào nó là anti-pattern)

Directive @apply của Tailwind cho phép bundle utility class vào CSS class name. Tailwind veteran sẽ bảo anh em tránh nó. Beginner thì reach for it bản năng. Đây là khi nào mỗi bên đúng.

Khi nào @apply ổn

Cross-cutting concern span toàn app: focus ring, transition dùng trong 20+ component, button reset style. Define .btn-primary một lần thì hơn hẳn repeat 8 utility class trong mọi JSX file.

.btn-primary {
  @apply px-4 py-2 bg-accent text-white rounded-lg
         hover:bg-accent/80 focus-visible:ring-2 focus-visible:ring-accent
         transition-colors;
}

Khi nào @apply là anti-pattern

Component-specific styling. Nếu class name miêu tả markup ("hero-headline", "card-footer"), anh em lost benefit chính của Tailwind — locality. Giờ phải switch file để hiểu styling.

Heuristic

Hỏi: "Tôi có dùng combination này ở 5+ nơi unrelated không?" Có → @apply. Không → inline utility tại JSX.

Đa số styling sống trong JSX. @apply cho vài pattern thực sự span toàn app.