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.1, we will look at a code snippet picked from packages/cli/src/index.ts.
In part 1.0, I discussed the imports used and getPackageInfo utility function. Let’s continue where we left off in part 1.0 by picking a code snippet that is in continuation to part 1.0
The below code snippet is picked from ui/packages/cli/src/index.ts
async function main() {
const packageInfo = await getPackageInfo()
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)
program.parse()
}
main()
new Command()
Commander package is used and is configured with name, description and version.
program.addCommand
After a new command is initialised, init, add and diff commands are added to the program variable using addCommand. You can specify (sub)commands using .command() or .addCommand(). There are two ways these can be implemented: using an action handler attached to the command, or as a stand-alone executable file.
program.parse
Parse function should be called with no parameters to parse process.argv via the CLI.
Conclusion:
In this article, I discussed a code snippet that deals with initialising command and adds custom commands such as init, add and diff that are used in shadcn-ui/ui CLI. I found out that program.parse() call with no arguments is important to parse the process.argv passed in via your CLI.
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)