shadcn-ui/ui codebase analysis: How does shadcn-ui CLI work? — Part 2.14
I wanted to find out how shadcn-ui CLI works. In this article, I discuss the code used to build the shadcn-ui/ui CLI.
In part 2.11, we looked at runInit function and how shadcn-ui/ui ensures directories provided in resolvedPaths in config exist.
The following operations are performed in runInit function:
#1, #2, #3 from the above are covered in part 2.12 and 2.13, let’s find out how “Write cn file” operation is done.
Write cn file
The below code snippet is picked from cli/src/commands/init.ts
// Write cn file.
await fs.writeFile(
`${config.resolvedPaths.utils}.${extension}`,
extension === "ts" ? templates.UTILS : templates.UTILS_JS,
"utf8"
)
templates.UTILS contains the below code
export const UTILS = `import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
`
export const UTILS_JS = `import { clsx } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs) {
return twMerge(clsx(inputs))
}
`
cn utility is literally code returned as a string and written to lib/utils when you run shadcn init.
领英推荐
Conclusion:
templates.UTILS variable in packages/cli/src/commands/init.ts contains the cn utility function related code.
export const UTILS = `import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
`
export const UTILS_JS = `import { clsx } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs) {
return twMerge(clsx(inputs))
}
`
Catch here is, this code is presented as a string into fs.writeFile that writes to a provided path as shown below
await fs.writeFile(
`${config.resolvedPaths.utils}.${extension}`,
extension === "ts" ? templates.UTILS : templates.UTILS_JS,
"utf8"
)
About me:
Website: https://ramunarasinga.com/
Email: [email protected]