cn README

The project's README from github.com/shadcn-ui/cn. As one markdown file: README.md.

cn

cn is a new engine for Tailwind class merging and conflict resolution. It replaces tailwind-merge and clsx. Same APIs. Full parity. And it is 30× faster.

import { cn } from "cn"

// conditional joining (like clsx) + conflict resolution (like tailwind-merge)
cn("px-2 py-1", isActive && "bg-blue-500", { "text-white": isActive })

cn has zero dependencies and is framework-agnostic: it works with React, Vue, Svelte, Solid, Astro, or plain server templates, and runs in browsers, Node, Bun, Deno, and edge runtimes. It works in any Tailwind CSS project. You don't need shadcn/ui.

cn is built and maintained by aidenybai and shadcn.

Can I use this today?

Yes. You can replace tailwind-merge and clsx with cn today. It's a drop-in replacement.

Here's a command to migrate:

npx shadcn@latest migrate cn

Install

npm i cn

New project

Import it and go. Nothing to configure:

import { cn } from "cn"

export function Button({
  className,
  active,
  ...props
}: React.ComponentProps<"button"> & { active?: boolean }) {
  return (
    <button
      className={cn(
        "rounded-md px-4 py-2 text-sm",
        active && "bg-primary",
        className
      )}
      {...props}
    />
  )
}

Existing shadcn/ui project

Using the shadcn CLI

npx shadcn@latest migrate cn

Manually

Your components already import cn from @/lib/utils. Replace the wrapper with the one from cn.

// lib/utils.ts
- import { clsx, type ClassValue } from "clsx";
- import { twMerge } from "tailwind-merge";

- export function cn(...inputs: ClassValue[]) {
-   return twMerge(clsx(inputs));
- }
+ export { cn } from "cn";

Then remove clsx and tailwind-merge from your dependencies. If other packages still import them, alias them to cn so your bundle only carries one implementation.

How much faster?

The following benchmarks compare cn against clsx + tailwind-merge, which is what most projects run today.

We ran each library through every workload in its own isolated process with its own warmup, and kept the best of 5 runs.

To see the results for yourself, run pnpm bench. The methodology is in docs/how-it-works.md.

scenario clsx + tailwind-merge cn faster
the call your components make most¹ 320 ns 10 ns 30×
same classes as last render (cache hit) 14 ns 7 ns 1.9×
typical component strings, warm 13 ns 7 ns 1.9×
thousands of recurring strings (a real repo's working set) 2.4 µs 14 ns 172×
cold render, many arbitrary values 3.4 µs 1.1 µs 3.0×
cold render, SSR-style unique strings 2.3 µs 360 ns 6.4×
very first call (page load) 3.2 ms 0.4 ms 7×

¹ cn(base, variant, condition && extra) with stable class strings. This is the shape almost every component call has. cn learns repeated call sequences, so a render loop's calls verify by identity and skip the work entirely.

Real repositories

The rows above are synthetic. pnpm bench:corpus replays every cn() call harvested from 58 open source codebases (144,265 calls) through each library, one isolated process per library and repository, and prints the per-repository table. Geometric mean across the 58 repositories: cn is 37× faster than clsx + tailwind-merge.

cn ships the least JavaScript to parse in every setup, 26 KB minified.

If you want an even smaller bundle with the same performance, see cn build.

Custom themes

cn/config accepts the same { extend, override, prefix } shape, under the same name:

// before
import { extendTailwindMerge } from "tailwind-merge"

const twMerge = extendTailwindMerge({
  extend: { classGroups: { "font-size": [{ text: ["hero"] }] } },
})
// after
import { createCn } from "cn/config"

const cn = createCn({
  extend: { classGroups: { "font-size": [{ text: ["hero"] }] } },
})

Custom validator functions work as-is. fromTheme, validators, mergeConfigs, and defaultConfig are exported from cn/config. Tailwind v4 prefixes are supported: createCn({ prefix: "tw" }).

Coming from tailwind-merge

cn produces the same output as tailwind-merge for every input. We verify this with 356,000 differential tests.

Every export maps to the same name or a familiar one:

tailwind-merge cn
twMerge(...) twMerge(...) from "cn", identical
twJoin(...) twJoin(...) from "cn", identical
extendTailwindMerge(ext) same name, from "cn/config"
createTailwindMerge(fn) createTwMerge(fn) from "cn/config"
getDefaultConfig() defaultConfig() from "cn/config"
fromTheme, validators same names, from "cn/config"
mergeConfigs same name, from "cn/config"
experimentalParseClassName not supported

Gotchas

API

Credits

Thank you to all three authors.

cn (shadcn-ui/cn)

Searching Database…

1.7K ·GitHub
Что это?cn — это новый движок объединения классов Tailwind CSS и разрешения конфликтов, который заменяет собой и tailwind-merge, и clsx: те же API, полностью идентичный вывод и гораздо более высокая скорость.
Это библиотека или фреймворк?Это небольшая библиотека JavaScript/TypeScript без зависимостей (плюс опциональный CLI), которая работает с любым фреймворком, поскольку не зависит от фреймворков.
Как добавить его в свой проект?В новом проекте просто импортируйте cn и используйте его. В существующем проекте shadcn/ui можно заменить его через shadcn CLI либо вручную заменить обёртку cn в @/lib/utils и удалить clsx и tailwind-merge из зависимостей.
Нужен ли именно Tailwind v4?Да — cn нацелен на Tailwind CSS v4 (как и tailwind-merge v3); если ваш проект на Tailwind v3, лучше остаться на tailwind-merge v2. Для CLI также нужен Node 20+.
Насколько cn на самом деле быстрее?В синтетических бенчмарках он быстрее clsx + tailwind-merge примерно в 1,9–172 раза в зависимости от сценария, а на корпусе из 144 265 реальных вызовов из 58 open source-репозиториев среднее геометрическое ускорение составляет 37×.
Не сломает ли переход мой существующий код на tailwind-merge?Нет, cn задуман как замена без правок кода: он выдаёт для любых входных данных результат, идентичный tailwind-merge, что подтверждено 356 000 дифференциальных тестов, и каждый экспорт соответствует тому же или привычному имени.
Для чего нужны cn build и cn/engine?cn build — это библиотека, стоящая за CLI и предназначенная для кастомных пайплайнов и плагинов сборщиков, а cn/engine (createEngine) позволяет компилировать таблицы на этапе сборки для ещё меньших специализированных бандлов.
Нужен ли shadcn/ui, чтобы этим пользоваться?Нет, cn работает в любом проекте Tailwind CSS и не требует shadcn/ui, хотя его создал и отчасти поддерживает автор shadcn/ui.
Creator
shadcn-ui
Size
1.9 MB
Stars
1.7K
Age
1mo
Commits · 90 Days