К основному содержанию
скилл Claude Code CX Codex Cursor GitHub Copilot официальный · Google

shadcn-ui · google-labs-code — скилл для Claude Code: что делает и как установить

Помогает находить, добавлять и настраивать компоненты shadcn/ui в React-проектах. Пригодится для сборки интерфейсов с Tailwind CSS.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add google-labs-code/stitch-skills --skill shadcn-ui -a claude-code
Открыть на GitHub

Что делает shadcn-ui

Скилл помогает искать компоненты shadcn/ui через MCP-инструменты, получать их метаданные и демо, а затем добавлять исходный код в проект. Для установки он использует npx shadcn@latest add [component-name]: файлы попадают в components/ui/, зависимости устанавливаются, а components.json обновляется. Для блоков предусмотрены отдельные операции поиска и получения исходников.

Для нового проекта есть npx shadcn@latest create, для существующего — npx shadcn@latest init. Скилл также описывает настройку cn(), тем, CSS-переменных, вариантов через class-variance-authority и обёрток в components/. Нужны React 18+, Tailwind CSS 3.0+, clsx, tailwind-merge, class-variance-authority и выбранные примитивы Radix UI или Base UI. Если проект не соответствует этим требованиям, это повод проверить конфигурацию до установки компонентов.

Какие задачи решает

  • найти подходящий компонент shadcn/ui
  • добавить компонент в components/ui/
  • получить метаданные и демо компонента
  • настроить тему и CSS-переменные
  • собрать UI-блок из нескольких файлов

Примеры запросов агенту

  • Найди компонент для диалогового окна через `list_components`, покажи его метаданные и демо.
  • Добавь компонент `button` в существующий проект и проверь нужные зависимости.
  • Инициализируй shadcn/ui через `npx shadcn@latest init`, затем настрой `cn()` и тему в `app/globals.css`.

Как установить shadcn-ui

1Через Skills CLI (Vercel)

npx skills add google-labs-code/stitch-skills --skill shadcn-ui -a claude-code

2Вручную: положить файлы

~/.claude/skills/shadcn-ui/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/shadcn-ui/

Из того же набора15

Весь набор →
design-md официальный google-labs-code Скилл выгружает экраны из Google Stitch через MCP-сервер и собирает файл DESIGN.md с описанием дизайн-системы, цветов и компонентов. Claude Code CX Codex Cursor +1 64 700установок enhance-prompt официальный google-labs-code Превращает неточные идеи интерфейса в детальные промпты для Google Stitch. Скилл подтягивает дизайн-систему из DESIGN.md и расписывает структуру экрана. Claude Code CX Codex Cursor +1 58 300установок stitch-loop официальный google-labs-code Организует автономную сборку страниц через Stitch MCP. Агент берёт задачу из файла-эстафеты, создаёт экран, переносит код в проект и сразу пишет задание для следующей итерации. Claude Code CX Codex Cursor +1 56 300установок stitch::react-components официальный google-labs-code Превращает дизайны Stitch в компоненты React с Vite. Также синхронизирует существующие компоненты с обновлёнными макетами. Claude Code CX Codex Cursor +1 50 400установок remotion официальный google-labs-code Собирает экраны проекта Stitch в ролик на Remotion с переходами, приближением и текстовыми подписями. Пригодится для демонстрации интерфейса по шагам. Claude Code CX Codex Cursor +1 41 300установок taste-design официальный google-labs-code Скилл формирует файл DESIGN.md для Google Stitch, задавая строгие дизайн-правила против шаблонных интерфейсов. Помогает настроить типографику, палитру и микроанимации для генерации экранов. Claude Code CX Codex Cursor +1 20 100установок stitch::generate-design официальный google-labs-code Скилл превращает текстовое описание или картинку в готовый экран интерфейса через Stitch MCP, а потом правит его точечными промптами. Claude Code CX Codex Cursor +1 10 700установок stitch::extract-design-md официальный google-labs-code Извлекает дизайн-систему в файл DESIGN.md прямо из исходников фронтенда без сборки проекта. Помогает перенести визуальные токены и правила вёрстки в формат Stitch. Claude Code CX Codex Cursor +1 10 500установок

Другие версии shadcn-ui

Похожие

remotion-render официальный Remotion Экспортирует видео и отдельные кадры из проектов Remotion через консольные команды. CX Codex GP ChatGPT 3установок remotion-create remotion-dev Скилл создаёт новый проект Remotion и помогает подготовить видеокомпозицию. Подойдёт, когда видео нужно собирать из React-разметки. Claude Code CX Codex Cursor +1 208 800установок remotion-captions remotion-dev Скилл для работы с субтитрами в Remotion: транскрипция видео, вывод и анимация подписей, импорт из .srt. Claude Code CX Codex Cursor +1 206 600установок remotion-markup remotion-dev Скилл задаёт правила написания React-разметки для Remotion: анимации через кадры, работа с медиа и эффектами. Пригодится, если вы собираете видео кодом. Claude Code CX Codex Cursor +1 202 600установок remotion-interactivity remotion-dev Подсказывает агенту, как размечать компоненты Remotion для редактирования в Remotion Studio. Пригодится при верстке видеосцен с настраиваемыми стилями, текстом и таймлайном. Claude Code CX Codex Cursor +1 197 900установок frontend-design официальный anthropics Скилл задаёт осмысленное визуальное направление для новых интерфейсов и редизайна. Подойдёт, когда стандартный шаблонный UI не устраивает. Claude Code Claude.ai 1 025 790установок design-taste-frontend Leonxlnx Скилл задаёт арт-дирекцию для публичных страниц и рабочих экранов, а затем проверяет результат в браузере по скриншотам. Нужен, когда интерфейс выглядит шаблонным или недоработанным. Claude Code CX Codex Cursor +1 673 100установок prototype Matt Pocock Создаёт временный прототип, чтобы проверить логику, модель состояния или вид интерфейса до работы над основным кодом. Claude Code 986 201установок

Вопросы о shadcn-ui

Как установить shadcn-ui в Claude Code?

Выполните шаги по порядку: npx skills add google-labs-code/stitch-skills --skill shadcn-ui -a claude-code, затем повторите npx skills add google-labs-code/stitch-skills --skill shadcn-ui -a claude-code, после этого откройте ~/.claude/skills/shadcn-ui/SKILL.md.

Что делает скилл shadcn-ui?

Он помогает находить компоненты и блоки shadcn/ui, получать их исходники и добавлять их в проект. Также он подсказывает, как настраивать тему, варианты компонентов и доступность.

Что нужно для работы shadcn-ui?

Компоненты рассчитаны на React 18+ и Tailwind CSS 3.0+. Также используются clsx, tailwind-merge, class-variance-authority и примитивы Radix UI или Base UI.

Исходный текст

SKILL.md · Apache-2.0
---
name: shadcn-ui
description: Expert guidance for integrating and building applications with shadcn/ui components, including component discovery, installation, customization, and best practices.
allowed-tools:
  - "shadcn*:*"
  - "mcp_shadcn*"
  - "Read"
  - "Write"
  - "Bash"
  - "web_fetch"
---

# shadcn/ui Component Integration

You are a frontend engineer specialized in building applications with shadcn/ui—a collection of beautifully designed, accessible, and customizable components built with Radix UI or Base UI and Tailwind CSS. You help developers discover, integrate, and customize components following best practices.

## Core Principles

shadcn/ui is **not a component library**—it's a collection of reusable components that you copy into your project. This gives you:
- **Full ownership**: Components live in your codebase, not node_modules
- **Complete customization**: Modify styling, behavior, and structure freely, including choosing between Radix UI or Base UI primitives
- **No version lock-in**: Update components selectively at your own pace
- **Zero runtime overhead**: No library bundle, just the code you need

## Component Discovery and Installation

### 1. Browse Available Components

Use the shadcn MCP tools to explore the component catalog and Registry Directory:
- **List all components**: Use `list_components` to see the complete catalog
- **Get component metadata**: Use `get_component_metadata` to understand props, dependencies, and usage
- **View component demos**: Use `get_component_demo` to see implementation examples

### 2. Component Installation

There are two approaches to adding components:

**A. Direct Installation (Recommended)**
```bash
npx shadcn@latest add [component-name]
```

This command:
- Downloads the component source code (adapting to your config: Radix vs Base UI)
- Installs required dependencies
- Places files in `components/ui/`
- Updates your `components.json` config

**B. Manual Integration**
1. Use `get_component` to retrieve the source code
2. Create the file in `components/ui/[component-name].tsx`
3. Install peer dependencies manually
4. Adjust imports if needed

### 3. Registry and Custom Registries

If working with a custom registry (defined in `components.json`) or exploring the Registry Directory:
- Use `get_project_registries` to list available registries
- Use `list_items_in_registries` to see registry-specific components
- Use `view_items_in_registries` for detailed component information
- Use `search_items_in_registries` to find specific components

## Project Setup

### Initial Configuration

For **new projects**, use the `create` command to customize everything (style, fonts, component library):

```bash
npx shadcn@latest create
```

For **existing projects**, initialize configuration:

```bash
npx shadcn@latest init
```

This creates `components.json` with your configuration:
- **style**: default, new-york (classic) OR choose new visual styles like Vega, Nova, Maia, Lyra, Mira
- **baseColor**: slate, gray, zinc, neutral, stone
- **cssVariables**: true/false for CSS variable usage
- **tailwind config**: paths to Tailwind files
- **aliases**: import path shortcuts
- **rsc**: Use React Server Components (yes/no)
- **rtl**: Enable RTL support (optional)

### Required Dependencies

shadcn/ui components require:
- **React** (18+)
- **Tailwind CSS** (3.0+)
- **Primitives**: Radix UI OR Base UI (depending on your choice)
- **class-variance-authority** (for variant styling)
- **clsx** and **tailwind-merge** (for class composition)

## Component Architecture

### File Structure
```
src/
├── components/
│   ├── ui/              # shadcn components
│   │   ├── button.tsx
│   │   ├── card.tsx
│   │   └── dialog.tsx
│   └── [custom]/        # your composed components
│       └── user-card.tsx
├── lib/
│   └── utils.ts         # cn() utility
└── app/
    └── page.tsx
```

### The `cn()` Utility

All shadcn components use the `cn()` helper for class merging:

```typescript
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}
```

This allows you to:
- Override default styles without conflicts
- Conditionally apply classes
- Merge Tailwind classes intelligently

## Customization Best Practices

### 1. Theme Customization

Edit your Tailwind config and CSS variables in `app/globals.css`:

```css
@layer base {
  :root {
    --background: 0 0% 100%;
    --foreground: 222.2 84% 4.9%;
    --primary: 221.2 83.2% 53.3%;
    /* ... more variables */
  }
  
  .dark {
    --background: 222.2 84% 4.9%;
    --foreground: 210 40% 98%;
    /* ... dark mode overrides */
  }
}
```

### 2. Component Variants

Use `class-variance-authority` (cva) for variant logic:

```typescript
import { cva } from "class-variance-authority"

const buttonVariants = cva(
  "inline-flex items-center justify-center rounded-md",
  {
    variants: {
      variant: {
        default: "bg-primary text-primary-foreground",
        outline: "border border-input",
      },
      size: {
        default: "h-10 px-4 py-2",
        sm: "h-9 rounded-md px-3",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "default",
    },
  }
)
```

### 3. Extending Components

Create wrapper components in `components/` (not `components/ui/`):

```typescript
// components/custom-button.tsx
import { Button } from "@/components/ui/button"
import { Loader2 } from "lucide-react"

export function LoadingButton({ 
  loading, 
  children, 
  ...props 
}: ButtonProps & { loading?: boolean }) {
  return (
    <Button disabled={loading} {...props}>
      {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
      {children}
    </Button>
  )
}
```

## Blocks and Complex Components

shadcn/ui provides complete UI blocks (authentication forms, dashboards, etc.):

1. **List available blocks**: Use `list_blocks` with optional category filter
2. **Get block source**: Use `get_block` with the block name
3. **Install blocks**: Many blocks include multiple component files

Blocks are organized by category:
- **calendar**: Calendar interfaces
- **dashboard**: Dashboard layouts
- **login**: Authentication flows
- **sidebar**: Navigation sidebars
- **products**: E-commerce components

## Accessibility

All shadcn/ui components are built on Radix UI primitives, ensuring:
- **Keyboard navigation**: Full keyboard support out of the box
- **Screen reader support**: Proper ARIA attributes
- **Focus management**: Logical focus flow
- **Disabled states**: Proper disabled and aria-disabled handling

When customizing, maintain accessibility:
- Keep ARIA attributes
- Preserve keyboard handlers
- Test with screen readers
- Maintain focus indicators

## Common Patterns

### Form Building
```typescript
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"

// Use with react-hook-form for validation
import { useForm } from "react-hook-form"
```

### Dialog/Modal Patterns
```typescript
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
```

### Data Display
```typescript
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
```

## Troubleshooting

### Import Errors
- Check `components.json` for correct alias configuration
- Verify `tsconfig.json` includes the `@` path alias:
  ```json
  {
    "compilerOptions": {
      "paths": {
        "@/*": ["./src/*"]
      }
    }
  }
  ```

### Style Conflicts
- Ensure Tailwind CSS is properly configured
- Check that `globals.css` is imported in your root layout
- Verify CSS variable names match between components and theme

### Missing Dependencies
- Run component installation via CLI to auto-install deps
- Manually check `package.json` for required Radix UI packages
- Use `get_component_metadata` to see dependency lists

### Version Compatibility
- shadcn/ui v4 requires React 18+ and Next.js 13+ (if using Next.js)
- Some components require specific Radix UI versions
- Check documentation for breaking changes between versions

## Validation and Quality

Before committing components:
1. **Type check**: Run `tsc --noEmit` to verify TypeScript
2. **Lint**: Run your linter to catch style issues
3. **Test accessibility**: Use tools like axe DevTools
4. **Visual QA**: Test in light and dark modes
5. **Responsive check**: Verify behavior at different breakpoints

## Resources

Refer to the following resource files for detailed guidance:
- `resources/setup-guide.md` - Step-by-step project initialization
- `resources/component-catalog.md` - Complete component reference
- `resources/customization-guide.md` - Theming and variant patterns
- `resources/migration-guide.md` - Upgrading from other UI libraries

## Examples

See the `examples/` directory for:
- Complete component implementations
- Form patterns with validation
- Dashboard layouts
- Authentication flows
- Data table implementations

© google-labs-code · Apache-2.0 · google-labs-code/stitch-skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой