>  기사  >  웹 프론트엔드  >  shadcn-ui/ui 코드베이스 분석: shadcn-ui CLI는 어떻게 작동하나요? — 3부

shadcn-ui/ui 코드베이스 분석: shadcn-ui CLI는 어떻게 작동하나요? — 3부

王林
王林원래의
2024-07-19 09:58:03567검색

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.11, we looked at runInit function and how shadcn-ui/ui ensures directories provided in resolvedPaths in config exist.

The following operations are performed in runInit function:

  1. Ensure all resolved paths directories exist.
  2. Write tailwind config.
  3. Write css file.
  4. Write cn file.
  5. Install dependencies.

1 and 2 from the above are covered in part 2.12, let’s find out how “Write css file” is done.

Write css file

The below code snippet is picked from packages/cli/src/commands/init.

// 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"
  )
}

baseColor is returned from getRegistryBaseColor and then using fs.writeFile, css code is written to the file located at path provided by config.resolvedPaths.tailwindCss.

getRegistryBaseColor

getRegistryBaseColor function is picked from src/utils/registry/index.ts

export async function getRegistryBaseColor(baseColor: string) {
  try {
    const \[result\] = await fetchRegistry(\[\`colors/${baseColor}.json\`\])

    return registryBaseColorSchema.parse(result)
  } catch (error) {
    throw new Error(\`Failed to fetch base color from registry.\`)
  }
}

An example baseColor json looks like below:

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

Result fetched is validated using registryBaseColorSchema.

applyPrefixesCss

shadcn-ui docs provides an option to provide tailwind prefix in components.json. You can read more about tailwind prefix from the tailwind docs.

export function applyPrefix(input: string, prefix: string = "") {
  const classNames = input.split(" ")
  const prefixed: string\[\] = \[\]
  for (let className of classNames) {
    const \[variant, value, modifier\] = splitClassName(className)
    if (variant) {
      modifier
        ? prefixed.push(\`${variant}:${prefix}${value}/${modifier}\`)
        : prefixed.push(\`${variant}:${prefix}${value}\`)
    } else {
      modifier
        ? prefixed.push(\`${prefix}${value}/${modifier}\`)
        : prefixed.push(\`${prefix}${value}\`)
    }
  }
  return prefixed.join(" ")
}


export function applyPrefixesCss(css: string, prefix: string) {
  const lines = css.split("\\n")
  for (let line of lines) {
    if (line.includes("@apply")) {
      const originalTWCls = line.replace("@apply", "").trim()
      const prefixedTwCls = applyPrefix(originalTWCls, prefix)
      css = css.replace(originalTWCls, prefixedTwCls)
    }
  }
  return css
}

Below is a cssVarsTemplate example picked from https://ui.shadcn.com/registry/colors/slate.json:

"cssVarsTemplate": "@tailwind base;\\n  @tailwind components;\\n  @tailwind utilities;\\n\\n  @layer base {\\n    :root {\\n      --background: 0 0% 100%;\\n      --foreground: 222.2 84% 4.9%;\\n      --card: 0 0% 100%;\\n      --card-foreground: 222.2 84% 4.9%;\\n      --popover: 0 0% 100%;\\n      --popover-foreground: 222.2 84% 4.9%;\\n      --primary: 222.2 47.4% 11.2%;\\n      --primary-foreground: 210 40% 98%;\\n      --secondary: 210 40% 96.1%;\\n      --secondary-foreground: 222.2 47.4% 11.2%;\\n      --muted: 210 40% 96.1%;\\n      --muted-foreground: 215.4 16.3% 46.9%;\\n      --accent: 210 40% 96.1%;\\n      --accent-foreground: 222.2 47.4% 11.2%;\\n      --destructive: 0 84.2% 60.2%;\\n      --destructive-foreground: 210 40% 98%;\\n      --border: 214.3 31.8% 91.4%;\\n      --input: 214.3 31.8% 91.4%;\\n      --ring: 222.2 84% 4.9%;\\n      --radius: 0.5rem;\\n      --chart-1: 12 76% 61%;\\n      --chart-2: 173 58% 39%;\\n      --chart-3: 197 37% 24%;\\n      --chart-4: 43 74% 66%;\\n      --chart-5: 27 87% 67%;\\n    }\\n\\n    .dark {\\n      --background: 222.2 84% 4.9%;\\n      --foreground: 210 40% 98%;\\n      --card: 222.2 84% 4.9%;\\n      --card-foreground: 210 40% 98%;\\n      --popover: 222.2 84% 4.9%;\\n      --popover-foreground: 210 40% 98%;\\n      --primary: 210 40% 98%;\\n      --primary-foreground: 222.2 47.4% 11.2%;\\n      --secondary: 217.2 32.6% 17.5%;\\n      --secondary-foreground: 210 40% 98%;\\n      --muted: 217.2 32.6% 17.5%;\\n      --muted-foreground: 215 20.2% 65.1%;\\n      --accent: 217.2 32.6% 17.5%;\\n      --accent-foreground: 210 40% 98%;\\n      --destructive: 0 62.8% 30.6%;\\n      --destructive-foreground: 210 40% 98%;\\n      --border: 217.2 32.6% 17.5%;\\n      --input: 217.2 32.6% 17.5%;\\n      --ring: 212.7 26.8% 83.9%;\\n      --chart-1: 220 70% 50%;\\n      --chart-2: 160 60% 45%;\\n      --chart-3: 30 80% 55%;\\n      --chart-4: 280 65% 60%;\\n      --chart-5: 340 75% 55%;\\n    }\\n  }\\n\\n  @layer base {\\n    \* {\\n      @apply border-border;\\n    }\\n    body {\\n      @apply bg-background text-foreground;\\n    }\\n  }"

Conclusion:

baseColor is returned from getRegistryBaseColor and then using fs.writeFile, css code is written to the file located at path provided by config.resolvedPaths.tailwindCss.

getRegistryBaseColor uses fetchRegistry to fetch the base color. An example baseColor.json is available at https://ui.shadcn.com/registry/colors/slate.json

components.json provides an option to configure prefix for your tailwind classes.

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:

  1. https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/commands/init.ts#L331C3-L356C4
  2. https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/utils/registry/index.ts#L64
  3. https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/utils/registry/index.ts#L139
  4. https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/utils/registry/schema.ts#L33
  5. https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/utils/transformers/transform-tw-prefix.ts#L191

위 내용은 shadcn-ui/ui 코드베이스 분석: shadcn-ui CLI는 어떻게 작동하나요? — 3부의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.