shadcn-ui/ui codebase analysis: How does shadcn-ui CLI work? — Part 2.0
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 1.0 and part 1.1, I discussed the code written in packages/cli/src/index.ts. In part 2.0, we will understand a code snippet from packages/cli/src/commands/init.ts
init command
We have seen that init
command is added to the program in the index.ts as shown below:
// https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/index.ts
const program = new Command()
.name("shadcn-ui")
.description("add components and dependencies to your project")
.version(
packageInfo.version || "1.0.0",
"-v, --version",
"display the version number"
)
program.addCommand(init).addCommand(add).addCommand(diff)
In this article, we will learn:
-
Access the CLI arguments using Commander.js
-
Parsing the CLI options with zod
Access the CLI arguments using Commander.js
I have created a minimal project setup that uses Commander.js, tsup and created folder structure that resembles with shadcn-ui/ui CLI package.
Execute the command node dist/index init -y -c -d
in the codesandbox console below to see accessing the CLI arguments in action.
Not sure why the codesandbox is not getting embedded here!
Repository link: https://github.com/Ramu-Narasinga/commanderjs-usage-in-shadcn-ui
Parsing the CLI options with zod
It is a good practice to have a schema defined using zod for your CLI options to parse and validate.
const initOptionsSchema = z.object({
cwd: z.string(),
yes: z.boolean(),
defaults: z.boolean(),
})
init
command first parses the CLI options provided to the init command
const options = initOptionsSchema.parse(opts)
const cwd = path.resolve(options.cwd)
Conclusion:
I created an example project on Github that demonstrates the usage of Commander.js, tsup and init command configuration in shadcn-ui/ui CLI package. These CLI options are parsed with zod before performing any further operations.
Want to learn how to build shadcn-ui/ui from scratch? Check out build-from-scratch
About me:
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.
I am open to work on interesting projects. Send me an email at ramu.narasinga@gmail.com
My Github — https://github.com/ramu-narasinga
My website — https://ramunarasinga.com
My Youtube channel — https://www.youtube.com/@thinkthroo
Learning platform — https://thinkthroo.com
Codebase Architecture — https://app.thinkthroo.com/architecture
Best practices — https://app.thinkthroo.com/best-practices
Production-grade projects — https://app.thinkthroo.com/production-grade-projects