Introduction

The cn API with macro compilation for cn, clsx, and twMerge.

twl provides cn, clsx, and twMerge with commented template support, with the matching ClassValue and ClassNameValue types. The twl/macro entry declares those same functions for build-time compilation and has no runtime exports.

Install

pnpm add twl

Runtime

import { cn, clsx, twMerge } from 'twl'

cn('p-2', { 'p-4': true }) // 'p-4'
clsx('p-2', { 'p-4': true }) // 'p-2 p-4'
twMerge('p-2', ['p-4']) // 'p-4'

Macros

import { cn, clsx, twMerge } from 'twl/macro'

const button = cn`
  // layout
  inline-flex items-center gap-2
  // spacing
  p-2 p-4
  ${variant}
`

clsx`p-2 p-4` // 'p-2 p-4': no conflict merging
twMerge`p-2 ${['p-4']}` // 'p-4'
cn('p-2', { 'p-4': true }) // ordinary calls still work

All three tags strip // comments at token boundaries and collapse whitespace. URLs and arbitrary values containing // remain intact. cn and clsx accept objects and arrays in interpolations. twMerge keeps its original argument types: strings, nested arrays, and supported empty values.

With a bundler plugin, static templates become strings; cn and twMerge resolve conflicts at build time. Dynamic templates retain the runtime helpers they need. Ordinary calls are redirected to twl/runtime. The macro entry requires the compiler plugin; import from twl to use templates directly at runtime.

The macro entry contains only type declarations for cn, clsx, and twMerge. Compiled code imports twl/runtime, which directly re-exports cn, clsx, and twMerge from cn. The twl entry provides template support.

Linting

eslint-plugin-twl and oxlint-plugin-twl sort classes inside each comment group and report, in the editor, the templates the compiler would refuse.

On this page