首页  >  文章  >  web前端  >  shadcn-ui/ui 代码库分析:shadcn-ui CLI 是如何工作的? - 部分

shadcn-ui/ui 代码库分析:shadcn-ui CLI 是如何工作的? - 部分

WBOY
WBOY原创
2024-07-18 14:11:581114浏览

我想了解 shadcn-ui CLI 是如何工作的。在本文中,我将讨论用于构建 shadcn-ui/ui CLI 的代码。

在第 2.8 部分中,我们研究了函数promptForMinimalConfig 及其参数,以及 shadcn-ui CLI 如何使用粉笔突出显示终端中的文本。

这是 2.8 的延续,我们将在本文中讨论以下概念。

  1. getRegistryStyles 函数
  2. fetchRegistry 函数
  3. 样式架构

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

getRegistryStyles 函数:

getRegistryStyles 是从 utils/registry/index.tsx 导入的。

export async function getRegistryStyles() {
  try {
    const \[result\] = await fetchRegistry(\["styles/index.json"\])

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

此函数获取样式注册表并使用样式模式解析结果。

获取注册表函数:

getRegistryStyles 使用参数 [“styles/index.json”] 调用 fetchRegistry 函数。为什么参数是数组?

async function fetchRegistry(paths: string\[\]) {
  try {
    const results = await Promise.all(
      paths.map(async (path) => {
        const response = await fetch(\`${baseUrl}/registry/${path}\`, {
          agent,
        })
        return await response.json()
      })
    )

    return results
  } catch (error) {
    console.log(error)
    throw new Error(\`Failed to fetch registry from ${baseUrl}.\`)
  }
}

注意参数是一个字符串数组。因为 fetchRegistry 使用 Promise.all 并基于使用 map 的路径循环进行获取。导航到 https://ui.shadcn.comstyles/index.json,您会发现调用 getRegistryStyles 时会获取以下 json。

shadcn-ui/ui 代码库分析:shadcn-ui CLI 是如何工作的? - 部分

样式模式

stylesSchema 是一个相当简单的模式,只有名称和标签。

export const stylesSchema = z.array(
  z.object({
    name: z.string(),
    label: z.string(),
  })
)

结论:

在本文中,我讨论了以下概念:

  1. getRegistryStyles 函数

getRegistryStyles 是从 utils/registry/index.tsx 导入的。此函数获取样式注册表并使用样式模式解析结果。

2. fetchRegistry 函数

getRegistryStyles 使用参数 [“styles/index.json”] 调用 fetchRegistry 函数。

为什么参数是数组?因为 fetchRegistry 使用 Promise.all 并根据使用 map 的路径循环进行获取。导航到 https://ui.shadcn.comstyles/index.json,您将找到调用 getRegistryStyles 时获取的与样式相关的 json。

3.样式架构

stylesSchema 是一个相当简单的模式,只有名称和标签。

export const stylesSchema = z.array(
  z.object({
    name: z.string(),
    label: z.string(),
  })
)

想学习如何从头开始构建 shadcn-ui/ui 吗?查看 从头开始构建

关于我:

网站:https://ramunarasinga.com/

Linkedin:https://www.linkedin.com/in/ramu-narasinga-189361128/

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

电子邮件:ramu.narasinga@gmail.com

从头开始构建 shadcn-ui/ui

参考:

  1. https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/utils/registry/index.ts#L29
  2. https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/utils/registry/index.ts#L139
  3. https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/utils/registry/schema.ts#L26

以上是shadcn-ui/ui 代码库分析:shadcn-ui CLI 是如何工作的? - 部分的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn