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.
Get free courses inspired by the best practices used in open source.
About me:
Website: https://ramunarasinga.com/
Linkedin: https://www.linkedin.com/in/ramu-narasinga-189361128/
Github: https://github.com/Ramu-Narasinga
Email: ramu.narasinga@gmail.com
Learn the best practices used in open source.
Top comments (0)