首頁  >  文章  >  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