入门指南

学习如何设置并运行您自己的组件注册表。

本指南将引导您完成设置个人组件注册表的全过程。

该指南假设您已拥有一个包含组件的项目,并希望将其转换为注册表。

registry.json

registry.json 文件仅在您使用 shadcn-vue CLI 构建注册表时必需。

若您使用其他构建系统,只要您的构建系统能生成符合 registry-item 模式规范 的有效 JSON 文件,即可跳过此步骤。

添加 registry.json 文件

在项目根目录下创建 registry.json 文件。您的项目可以是 Nuxt、Vite 或任何其他支持 Vue 的项目。

registry.json
json
{
  "$schema": "https://shadcn-vue.com/schema/registry.json",
  "name": "acme",
  "homepage": "https://acme.com",
  "items": [
    // ...
  ]
}

registry.json 文件必须符合 注册表模式规范

添加注册表项

创建您的组件

添加您的第一个组件。以下是一个简单的 <HelloWorld /> 组件示例:

registry/new-york/HelloWorld/HelloWorld.vue
vue
<script setup lang="ts">
import { Button } from "@/components/ui/button"
</script>

<template>
  <Button>Hello World</Button>
</template>
txt
registry
└── new-york
    └── HelloWorld
        └── HelloWorld.vue

将组件添加到注册表

要将组件添加到注册表,您需要在 registry.json 中添加组件定义。

registry.json
json
{
  "$schema": "https://shadcn-vue.com/schema/registry.json",
  "name": "acme",
  "homepage": "https://acme.com",
  "items": [
    {
      "name": "hello-world",
      "type": "registry:block",
      "title": "Hello World",
      "description": "一个简单的 hello world 组件。",
      "files": [
        {
          "path": "registry/new-york/HelloWorld/HelloWorld.vue",
          "type": "registry:component"
        }
      ]
    }
  ]
}

您需要为注册表项定义 nametypetitledescriptionfiles

对于添加的每个文件,必须指定其 pathtypepath 是从项目根目录到该文件的相对路径,type 是文件的类型。

您可以在 注册表项模式文档 中了解更多关于注册表项模式和文件类型的信息。

构建您的注册表

安装 shadcn-vue CLI

注意:build 命令目前仅在 shadcn-vue@canary 版本的 CLI 中可用。

pnpm add shadcn-vue@latest

添加构建脚本

package.json 文件中添加 registry:build 脚本。

package.json
json
{
  "scripts": {
    "registry:build": "shadcn-vue build"
  }
}

运行构建脚本

运行构建脚本以生成注册表 JSON 文件。

pnpm registry:build

提供您的注册表服务

如果您在 Nuxt 上运行注册表,现在可以通过运行 nuxt 服务器来提供注册表服务。其他框架的命令可能有所不同。

pnpm dev

您的文件现在将在 http://localhost:3000/r/[NAME].json 地址提供服务,例如 http://localhost:3000/r/hello-world.json

发布您的注册表

为了让其他开发者可以使用您的注册表,您可以通过将项目部署到公共 URL 来发布它。

添加认证

shadcn-vue CLI 不提供内置方法来为您的注册表添加认证。我们建议在您的注册表服务器上处理授权。

一种常见的简单方法是使用 token 查询参数来认证对注册表的请求,例如 http://localhost:3000/r/hello-world.json?token=[SECURE_TOKEN_HERE]

使用安全令牌来认证请求,并在令牌无效时返回 401 Unauthorized 响应。shadcn CLI 和 Open in v0 都会处理 401 响应并向用户显示消息。

指南

以下是为注册表构建组件时应遵循的一些指南。

  • 将您的注册表项放置在 registry/[STYLE]/[NAME] 目录中。我以 new-york 为例。它可以是您想要的任何名称,只要它嵌套在 registry 目录下即可。
  • 块定义必需包含以下属性:namedescriptiontypefiles
  • 确保在 registryDependencies 中列出所有注册表依赖项。注册表依赖项可以是注册表中组件的名称,例如 inputbuttoncard 等,也可以是注册表项的 URL,例如 http://localhost:3000/r/editor.json
  • 确保在 dependencies 中列出所有依赖项。依赖项是注册表中包的名称,例如 zodsonner 等。要设置版本,可以使用 name@version 格式,例如 zod@^3.20.0
  • 导入应始终使用 @/registry 路径。 例如:import { HelloWorld } from "@/registry/new-york/hello-world/hello-world"
  • 理想情况下,将您的文件放置在注册表项内的 componentshookslib 目录中。

使用 CLI 安装

要使用 shadcn-vue CLI 安装注册表项,请使用 add 命令后跟注册表项的 URL。

pnpm dlx shadcn-vue@latest add http://localhost:3000/r/hello-world.json
Edit this page on GitHub