Tailwind Variant v3

0.2.1 · active · verified Tue Apr 21

The `tailwind-variant-v3` package is a runtime variant utility specifically designed for Tailwind CSS v3, offering a TypeScript-first approach for defining and managing UI component styles. It is part of the `weapp-tailwindcss` monorepo, which integrates Tailwind CSS into WeChat Mini Programs and similar environments. The current stable version is `0.2.1`. Key features include composable variants (supporting `base`, `slots`, `variants`, `compoundVariants`, `compoundSlots`), responsive variant definitions, and deep integration with `tailwind-merge` for robust class name collision resolution. It provides `cn` and `cnBase` utilities and allows for custom `twMergeConfig` and pluggable `twMergeAdapter` implementations for alternative merging libraries. Slot caching is also incorporated to optimize performance. Users must manually install `tailwind-merge@^2` as a peer dependency. For projects using Tailwind CSS v4, it is explicitly recommended to use a corresponding v4 runtime variant solution.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a button component using `tv` with base styles, slots, variants, and default variants. It then shows how to generate and access specific slot classes and how to use the `cn` utility for merging arbitrary class names.

import { cn, tv } from 'tailwind-variant-v3'

const button = tv({
  base: 'inline-flex items-center gap-2 font-medium transition-colors',
  slots: {
    icon: 'size-4',
    label: 'truncate'
  },
  variants: {
    tone: {
      primary: 'bg-blue-500 text-white hover:bg-blue-600',
      secondary: 'bg-zinc-900 text-zinc-50 hover:bg-zinc-800',
      ghost: 'bg-transparent text-zinc-900 hover:bg-zinc-100'
    },
    size: {
      sm: { base: 'h-8 px-3 text-xs', icon: 'size-3' },
      md: { base: 'h-10 px-4 text-sm', icon: 'size-4' },
      lg: { base: 'h-12 px-6 text-base', icon: 'size-5' }
    }
  },
  defaultVariants: {
    tone: 'primary',
    size: 'md'
  }
})

// Generate slot classes for a ghost, large button
const slots = button({ tone: 'ghost', size: 'lg' })

// Access individual slot classes
const baseClasses = slots.base() // Example: 'inline-flex items-center gap-2 font-medium transition-colors h-12 px-6 text-base'
const iconClasses = slots.icon({ class: 'text-xl' }) // Example: 'size-5 text-xl'

// Use cn for general class merging
const combinedClasses = cn('flex', ['text-sm', 'md:text-lg'])({ twMerge: true })

console.log('Base Classes:', baseClasses)
console.log('Icon Classes:', iconClasses)
console.log('Combined Classes:', combinedClasses)

view raw JSON →