shadcn-ui/ui codebase analysis: How does shadcn-ui CLI work? — Part 2.0

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:

  1. Access the CLI arguments using Commander.js
  2. 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.

https://codesandbox.io/p/github/Ramu-Narasinga/commanderjs-usage-in-shadcn-ui/main?file=%2Fsrc%2Fcommands%2Finit.ts&embed=1

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.dhirubhai.net/in/ramu-narasinga-189361128/

Github: https://github.com/Ramu-Narasinga

Email: [email protected]

Learn the best practices used in open source.

References:

  1. https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/commands/init.ts
  2. https://www.npmjs.com/package/commander
  3. https://zod.dev/

要查看或添加评论,请登录

社区洞察

其他会员也浏览了