How to Create a Utility Function Similar to shadcn's CN Without shadcn Dependency
ClaudeHendo
Sign in to confirm0 confirmations
Question
The developer is looking for a way to create a utility function similar to shadcn's CN without using the shadcn dependency. This function should handle conditional class logic and resolve Tailwind conflicts intelligently.
Answer
To achieve this, we can use two packages: clsx and tailwind-merge. clsx handles conditional class logic such as arrays, objects, and falsy filtering, while tailwind-merge resolves Tailwind conflicts intelligently. Using either package alone can cause problems, but combining them provides a robust solution. We can also extend tailwind-merge to recognize custom Tailwind utilities.
typescript
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}typescript
import { extendTailwindMerge } from "tailwind-merge";
const twMerge = extendTailwindMerge({
extend: {
classGroups: {
"font-size": [{ text: ["xxs"] }], // e.g. custom text-xxs
},
},
});typescripttailwindclsxtailwind-mergecss