shadcn-ui/ui codebase analysis: How does shadcn-ui CLI work? — Part 2.11
Tags: javascript, opensource, nextjs, shadcnui
Published: 2024-07-11 21:06:53

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.

![](https://media.licdn.com/dms/image/D4E12AQHMep_GdbUeeg/article-inline_image-shrink_1500_2232/0/1720731575693?e=1726099200&v=beta&t=FrPMvm3oq3O29Y7TdPUau6yO7TEKonZo4X1YIHZ9xxU)

Now that we understood how promptForMinimalConfig function works, it is time we move onto find out how runInit function works.

runInit
-------
```js
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.

1.  Ensure all resolved paths directories exist.
2.  Write tailwind config.
3.  Write css file.
4.  Write cn file.
5.  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.
--------------------------------------------
```js
// 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.

![](https://media.licdn.com/dms/image/D4E12AQG4hvXlYwfr2A/article-inline_image-shrink_1000_1488/0/1720731578351?e=1726099200&v=beta&t=UwRl5er-fe2O5Yg-lFvDwYxkDlWHoMWW0P42fMaxGUc)

```js
// 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](https://www.npmjs.com/package/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.

```js
// 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.

```js
if (!existsSync(dirname)) {
  await fs.mkdir(dirname, { recursive: true })
}
```

[existsSync](https://nodejs.org/api/fs.html#fsexistssyncpath) 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:

1.  Ensure all resolved paths directories exist.
2.  Write tailwind config.
3.  Write css file.
4.  Write cn file.
5.  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_](https://tthroo.com/)

About me:
---------

Website: [https://ramunarasinga.com/](https://ramunarasinga.com/)

Linkedin: [https://www.linkedin.com/in/ramu-narasinga-189361128/](https://www.linkedin.com/in/ramu-narasinga-189361128/)

Github: [https://github.com/Ramu-Narasinga](https://github.com/Ramu-Narasinga)

Email: [ramu.narasinga@gmail.com](mailto:ramu.narasinga@gmail.com)

[Build shadcn-ui/ui from scratch](https://tthroo.com/)

References:
-----------

1.  [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#L81)
2.  [https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/commands/init.ts#L307](https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/commands/init.ts#L307)