cn-codemod
v1.0.0
Published
NPX tool to migrate React className template literals to the cn() utility function (clsx + tailwind-merge)
Downloads
117
Maintainers
Readme
cn-codemod
An NPX tool to migrate React className template literals to the cn() utility function (powered by clsx + tailwind-merge).
What it does
Transforms this:
<div
className={`flex items-center ${isActive ? "text-blue-500" : "text-gray-500"}`}
/>Into this:
import { cn } from "@/utils/cn";
<div
className={cn(
"flex items-center",
isActive ? "text-blue-500" : "text-gray-500",
)}
/>;It also automatically adds the cn import to each file that needs it.
Requirements
- React project with Tailwind CSS
- Node.js 14+
Usage
Run from your project root:
npx cn-codemodOptions
| Flag | Description | Default |
| -------------------- | --------------------------------------- | ------------ |
| --src <dir> | Source directory to scan | src |
| --cn-import <path> | Import alias path for cn | @/utils/cn |
| --create-cn | Create the cn utility file if missing | — |
| -h, --help | Show help | — |
Examples
# Run with defaults (scans ./src, imports from @/utils/cn)
npx cn-codemod
# Custom source directory and import path
npx cn-codemod --src app --cn-import "@/lib/utils"
# Auto-create the cn utility file too
npx cn-codemod --create-cnSetting up the cn utility
The cn function combines clsx and tailwind-merge to safely merge Tailwind class names:
// src/utils/cn.ts
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}You can either create this file manually, or let the tool create it for you with --create-cn.
If using --create-cn, make sure to install the dependencies:
npm install clsx tailwind-mergeLicense
MIT
