


shadcn-ui/ui codebase analysis: How does shadcn-ui CLI work? — Part 1
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.10, we looked at getRegistryBaseColors function, prompts, creating components.json and resolveConfigPaths.
Now that we understood how promptForMinimalConfig function works, it is time we move onto find out how runInit function works.
runInit
export async function runInit(cwd: string, config: Config) { const spinner = ora(\`Initializing project...\`)?.start() // Ensure all resolved paths directories exist. for (const \[key, resolvedPath\] of Object.entries(config.resolvedPaths)) { // Determine if the path is a file or directory. // TODO: is there a better way to do this? let dirname = path.extname(resolvedPath) ? path.dirname(resolvedPath) : resolvedPath // If the utils alias is set to something like "@/lib/utils", // assume this is a file and remove the "utils" file name. // TODO: In future releases we should add support for individual utils. if (key === "utils" && resolvedPath.endsWith("/utils")) { // Remove /utils at the end. dirname = dirname.replace(/\\/utils$/, "") } if (!existsSync(dirname)) { await fs.mkdir(dirname, { recursive: true }) } } const extension = config.tsx ? "ts" : "js" const tailwindConfigExtension = path.extname( config.resolvedPaths.tailwindConfig ) let tailwindConfigTemplate: string if (tailwindConfigExtension === ".ts") { tailwindConfigTemplate = config.tailwind.cssVariables ? templates.TAILWIND\_CONFIG\_TS\_WITH\_VARIABLES : templates.TAILWIND\_CONFIG\_TS } else { tailwindConfigTemplate = config.tailwind.cssVariables ? templates.TAILWIND\_CONFIG\_WITH\_VARIABLES : templates.TAILWIND\_CONFIG } // Write tailwind config. await fs.writeFile( config.resolvedPaths.tailwindConfig, template(tailwindConfigTemplate)({ extension, prefix: config.tailwind.prefix, }), "utf8" ) // Write css file. const baseColor = await getRegistryBaseColor(config.tailwind.baseColor) if (baseColor) { await fs.writeFile( config.resolvedPaths.tailwindCss, config.tailwind.cssVariables ? config.tailwind.prefix ? applyPrefixesCss(baseColor.cssVarsTemplate, config.tailwind.prefix) : baseColor.cssVarsTemplate : baseColor.inlineColorsTemplate, "utf8" ) } // Write cn file. await fs.writeFile( \`${config.resolvedPaths.utils}.${extension}\`, extension === "ts" ? templates.UTILS : templates.UTILS\_JS, "utf8" ) spinner?.succeed() // Install dependencies. const dependenciesSpinner = ora(\`Installing dependencies...\`)?.start() const packageManager = await getPackageManager(cwd) // TODO: add support for other icon libraries. const deps = \[ ...PROJECT\_DEPENDENCIES, config.style === "new-york" ? "@radix-ui/react-icons" : "lucide-react", \] await execa( packageManager, \[packageManager === "npm" ? "install" : "add", ...deps\], { cwd, } ) dependenciesSpinner?.succeed() }
This function is rather large, let’s break this analysis down by studying small code chunks.
Well, this code already has some comments added that are specific to the operations. We can follow the same comments to break this analysis down into parts.
- Ensure all resolved paths directories exist.
- Write tailwind config.
- Write css file.
- Write cn file.
- Install dependencies.
In this article, let’s find out how shadcn-ui/ui CLI ensures all resolved paths directories exist.
Ensure all resolved paths directories exist.
// Ensure all resolved paths directories exist. for (const \[key, resolvedPath\] of Object.entries(config.resolvedPaths)) { // Determine if the path is a file or directory. // TODO: is there a better way to do this? let dirname = path.extname(resolvedPath) ? path.dirname(resolvedPath) : resolvedPath // If the utils alias is set to something like "@/lib/utils", // assume this is a file and remove the "utils" file name. // TODO: In future releases we should add support for individual utils. if (key === "utils" && resolvedPath.endsWith("/utils")) { // Remove /utils at the end. dirname = dirname.replace(/\\/utils$/, "") } if (!existsSync(dirname)) { await fs.mkdir(dirname, { recursive: true }) } }
In article 2.10, I talked about how config has resolvedPaths object is added.
// Determine if the path is a file or directory. // TODO: is there a better way to do this? let dirname = path.extname(resolvedPath) ? path.dirname(resolvedPath) : resolvedPath
The above code uses path. The path.extname() method returns the extension of the path, from the last occurrence of the . (period) character to end of string in the last portion of the path. If there is no . in the last portion of the path, or if there are no . characters other than the first character of the basename of path (see path.basename()) , an empty string is returned.
// If the utils alias is set to something like "@/lib/utils", // assume this is a file and remove the "utils" file name. // TODO: In future releases we should add support for individual utils. if (key === "utils" && resolvedPath.endsWith("/utils")) { // Remove /utils at the end. dirname = dirname.replace(/\\/utils$/, "") }
The comment in the above code explains it all.
if (!existsSync(dirname)) { await fs.mkdir(dirname, { recursive: true }) }
existsSync is a function from “fs” package, returns true if the path exists, false otherwise.
if the directory does not exist, fs.mkdir is used to create the directory.
Conclusion:
Now that I understood how promptForMinimalConfig function works, it is time to move onto finding out how runInit function works in the shadcn-ui/ui CLI related source code.
runInit function is rather large, let’s break this analysis down by studying small code chunks. This already has some comments explaining what it does. These operations with comments are as follows:
- Ensure all resolved paths directories exist.
- Write tailwind config.
- Write css file.
- Write cn file.
- Install dependencies.
I discussed how shadcn’s init command ensures all resolved paths directories exist by using existsSync from “fs” package, if the directory does not exist, this function simply creates a new dir using mkdir.
Want to learn how to build shadcn-ui/ui from scratch? Check out build-from-scratch
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
Build shadcn-ui/ui from scratch
References:
- https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/commands/init.ts#L81
- https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/commands/init.ts#L307
The above is the detailed content of shadcn-ui/ui codebase analysis: How does shadcn-ui CLI work? — Part 1. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.
