tailwind-shadcn-ui-setup
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTailwind + shadcn/ui Setup for Next.js 16
Next.js 16 项目的 Tailwind + shadcn/ui 配置指南
Overview
概述
Configure a production-ready Tailwind CSS (v3/v4) + shadcn/ui setup for Next.js 16 App Router projects. This skill automates dependency installation, configuration, component generation, and provides:
- Tailwind CSS v4-ready configuration (v3 with forward-compatible patterns)
- shadcn/ui components (Radix UI-based, fully accessible)
- Dark mode with (class strategy)
next-themes - Base application layout (header, optional sidebar, responsive)
- Design token system (CSS variables for easy theming)
- Accessibility defaults (WCAG 2.1 AA compliant)
- Example pages (forms, dialogs, theme showcase)
为Next.js 16 App Router项目配置生产就绪的Tailwind CSS(v3/v4)+ shadcn/ui环境。本技能可自动化依赖安装、配置和组件生成,并提供以下功能:
- 兼容Tailwind CSS v4的配置(v3版本采用向前兼容的模式)
- shadcn/ui组件(基于Radix UI,完全支持无障碍访问)
- 暗色模式(使用,采用类策略)
next-themes - 基础应用布局(头部、可选侧边栏,响应式设计)
- 设计令牌系统(通过CSS变量实现轻松主题定制)
- 无障碍默认设置(符合WCAG 2.1 AA标准)
- 示例页面(表单、对话框、主题展示)
Prerequisites
前置条件
Before running this skill, verify:
- Next.js 16 project exists with App Router (directory)
app/ - Package manager: npm (script uses )
npm install - Project structure: Valid at project root
package.json - TypeScript: Recommended (all templates use /
.tsx).ts
To verify:
bash
undefined运行本技能前,请确认:
- 已存在Next.js 16项目且使用App Router(包含目录)
app/ - 包管理器:npm(脚本使用)
npm install - 项目结构:项目根目录下有有效的
package.json - TypeScript:推荐使用(所有模板均使用/
.tsx).ts
验证方式:
bash
undefinedCheck Next.js version
检查Next.js版本
cat package.json | grep ""next":"
cat package.json | grep ""next":"
Confirm app/ directory exists
确认app/目录存在
ls -la app/
undefinedls -la app/
undefinedSetup Workflow
配置流程
Step 1: Gather User Requirements
步骤1:收集用户需求
Use tool to collect configuration preferences:
AskUserQuestion- Enable dark mode? (default: yes)
- Installs , adds
next-themes, creates mode toggleThemeProvider
- Installs
- Theme preset (zinc | slate | neutral, default: zinc)
- Determines base color palette in CSS variables
- Include sidebar layout? (default: yes)
- Adds responsive sidebar navigation using component
Sheet
- Adds responsive sidebar navigation using
- Include example pages? (default: yes)
- Generates example pages for forms, dialogs, theme showcase
使用工具收集配置偏好:
AskUserQuestion- 是否启用暗色模式?(默认:是)
- 安装,添加
next-themes,创建模式切换按钮ThemeProvider
- 安装
- 主题预设(zinc | slate | neutral,默认:zinc)
- 决定CSS变量中的基础调色板
- 是否包含侧边栏布局?(默认:是)
- 使用组件添加响应式侧边栏导航
Sheet
- 使用
- 是否包含示例页面?(默认:是)
- 生成表单、对话框、主题展示的示例页面
Step 2: Run Automation Script
步骤2:运行自动化脚本
Execute the Python setup script to install dependencies and initialize shadcn/ui:
bash
cd /path/to/nextjs-project
python /path/to/skill/scripts/setup_tailwind_shadcn.pyThe script will:
- Detect existing Tailwind/shadcn installations
- Install required npm packages (non-interactive)
- Create for shadcn/ui
components.json - Add baseline shadcn components (button, card, input, label, dialog, separator)
- Create with
lib/utils.tshelpercn()
执行Python配置脚本以安装依赖并初始化shadcn/ui:
bash
cd /path/to/nextjs-project
python /path/to/skill/scripts/setup_tailwind_shadcn.py脚本将:
- 检测已有的Tailwind/shadcn安装
- 安装所需的npm包(非交互式)
- 创建shadcn/ui的
components.json - 添加基础shadcn组件(按钮、卡片、输入框、标签、对话框、分隔符)
- 创建包含工具函数的
cn()lib/utils.ts
Step 3: Copy Configuration Files
步骤3:复制配置文件
Copy and process template files from directory:
assets/-
Tailwind Configurationbash
# Copy and create cp assets/tailwind.config.ts.template project/tailwind.config.ts cp assets/postcss.config.js.template project/postcss.config.js -
Global Stylesbash
# Copy and replace {{THEME_PRESET}} with user's choice cp assets/globals.css.template project/app/globals.css # Replace: {{THEME_PRESET}} → zinc | slate | neutral -
Utility Functionsbash
cp assets/lib/utils.ts project/lib/utils.ts
从目录复制并处理模板文件:
assets/-
Tailwind配置bash
# 复制并创建 cp assets/tailwind.config.ts.template project/tailwind.config.ts cp assets/postcss.config.js.template project/postcss.config.js -
全局样式bash
# 复制并将{{THEME_PRESET}}替换为用户选择的主题 cp assets/globals.css.template project/app/globals.css # 替换规则:{{THEME_PRESET}} → zinc | slate | neutral -
工具函数bash
cp assets/lib/utils.ts project/lib/utils.ts
Step 4: Add Core Components
步骤4:添加核心组件
Copy theme and layout components from :
assets/components/-
Theme Provider (if dark mode enabled)bash
cp assets/components/theme-provider.tsx project/components/theme-provider.tsx cp assets/components/mode-toggle.tsx project/components/mode-toggle.tsx -
App Shell (if sidebar layout enabled)bash
cp assets/components/app-shell.tsx project/components/app-shell.tsx
从复制主题和布局组件:
assets/components/-
主题提供者(若启用暗色模式)bash
cp assets/components/theme-provider.tsx project/components/theme-provider.tsx cp assets/components/mode-toggle.tsx project/components/mode-toggle.tsx -
应用外壳(若启用侧边栏布局)bash
cp assets/components/app-shell.tsx project/components/app-shell.tsx
Step 5: Update App Layout
步骤5:更新应用布局
Update or create :
app/layout.tsxbash
undefined更新或创建:
app/layout.tsxbash
undefinedIf layout.tsx exists, carefully merge changes
若layout.tsx已存在,请谨慎合并更改
If not, copy template
若不存在,复制模板
cp assets/app/layout.tsx.template project/app/layout.tsx
**Key additions:**
- Import `globals.css`
- Wrap with `ThemeProvider` (if dark mode enabled)
- Add skip link for accessibility
- Include `<Toaster />` from Sonner for notifications
**Merge strategy if layout exists:**
- Add missing imports at top
- Wrap existing content with `ThemeProvider`
- Add skip link before main content
- Add `Toaster` before closing `body` tag
- Ensure `suppressHydrationWarning` on `<html>` tagcp assets/app/layout.tsx.template project/app/layout.tsx
**关键新增内容:**
- 导入`globals.css`
- 用`ThemeProvider`包裹内容(若启用暗色模式)
- 添加无障碍跳转链接
- 包含Sonner的`<Toaster />`用于通知
**若布局已存在的合并策略:**
- 在顶部添加缺失的导入
- 用`ThemeProvider`包裹现有内容
- 在主内容前添加跳转链接
- 在`body`闭合标签前添加`Toaster`
- 确保`<html>`标签包含`suppressHydrationWarning`属性Step 6: Generate Example Pages (Optional)
步骤6:生成示例页面(可选)
If user requested examples, copy example pages:
bash
undefined若用户要求示例,复制示例页面:
bash
undefinedCopy home page
复制主页
cp assets/app/page.tsx.template project/app/page.tsx
cp assets/app/page.tsx.template project/app/page.tsx
Copy examples directory structure
复制示例目录结构
cp -r assets/app/examples/ project/app/examples/
**Example pages include:**
- **Homepage** (`app/page.tsx`): Hero, features grid, CTA
- **Forms** (`app/examples/forms/page.tsx`): Contact form, validation patterns
- **Dialogs** (`app/examples/dialogs/page.tsx`): Modal examples, A11y notes
- **Theme** (`app/examples/theme/page.tsx`): Color tokens, customization guidecp -r assets/app/examples/ project/app/examples/
**示例页面包括:**
- **主页** (`app/page.tsx`):Hero区域、功能网格、CTA按钮
- **表单** (`app/examples/forms/page.tsx`):联系表单、验证模式
- **对话框** (`app/examples/dialogs/page.tsx`):模态框示例、无障碍说明
- **主题** (`app/examples/theme/page.tsx`):颜色令牌、定制指南Step 7: Add Additional shadcn Components
步骤7:添加更多shadcn组件
Install additional components as needed:
bash
undefined根据需要安装额外组件:
bash
undefinedCommon components for examples
示例中常用的组件
npx shadcn-ui@latest add dropdown-menu
npx shadcn-ui@latest add sheet
npx shadcn-ui@latest add separator
npx shadcn-ui@latest add dropdown-menu
npx shadcn-ui@latest add sheet
npx shadcn-ui@latest add separator
Optional: Form components
可选:表单组件
npx shadcn-ui@latest add form
npx shadcn-ui@latest add checkbox
npx shadcn-ui@latest add select
Consult `references/shadcn-component-list.md` for full component catalog.npx shadcn-ui@latest add form
npx shadcn-ui@latest add checkbox
npx shadcn-ui@latest add select
完整组件目录请参考`references/shadcn-component-list.md`。Step 8: Verify Installation
步骤8:验证安装
Run checks to ensure setup is complete:
bash
undefined运行检查以确保配置完成:
bash
undefinedCheck for TypeScript errors
检查TypeScript错误
npx tsc --noEmit
npx tsc --noEmit
Start dev server
启动开发服务器
npm run dev
npm run dev
Open browser to http://localhost:3000
在浏览器中打开 http://localhost:3000
**Visual verification:**
- Page loads without errors
- Dark mode toggle works (if enabled)
- Colors match theme preset
- Example pages render correctly (if included)
- No accessibility warnings in console
**视觉验证:**
- 页面加载无错误
- 暗色模式切换正常(若启用)
- 颜色与主题预设匹配
- 示例页面渲染正确(若包含)
- 控制台无无障碍警告Step 9: Document Changes
步骤9:记录更改
Add a "Design System & UI" section to project :
README.mdmarkdown
undefined在项目中添加“设计系统与UI”章节:
README.mdmarkdown
undefinedDesign System & UI
设计系统与UI
This project uses Tailwind CSS and shadcn/ui for styling and components.
本项目使用Tailwind CSS和shadcn/ui进行样式设计和组件开发。
Customizing Colors
自定义颜色
Edit CSS variables in :
app/globals.csscss
:root {
--primary: 270 80% 45%; /* Your brand color (HSL) */
--radius: 0.75rem; /* Border radius */
}Test contrast ratios: https://webaim.org/resources/contrastchecker/
编辑中的CSS变量:
app/globals.csscss
:root {
--primary: 270 80% 45%; /* 你的品牌颜色(HSL格式) */
--radius: 0.75rem; /* 边框圆角 */
}Adding Components
添加组件
bash
undefinedbash
undefinedAdd any shadcn/ui component
添加任意shadcn/ui组件
npx shadcn-ui@latest add [component-name]
npx shadcn-ui@latest add [component-name]
Example: Add a combobox
示例:添加组合框
npx shadcn-ui@latest add combobox
Available components: https://ui.shadcn.com/docs/componentsnpx shadcn-ui@latest add combobox
可用组件:https://ui.shadcn.com/docs/componentsDark Mode
暗色模式
Toggle theme programmatically:
tsx
import { useTheme } from 'next-themes'
export function Example() {
const { theme, setTheme } = useTheme()
// theme: 'light' | 'dark' | 'system'
// setTheme('dark')
}通过代码切换主题:
tsx
import { useTheme } from 'next-themes'
export function Example() {
const { theme, setTheme } = useTheme()
// theme: 'light' | 'dark' | 'system'
// setTheme('dark')
}Accessibility
无障碍访问
- All components meet WCAG 2.1 Level AA
- Focus indicators on all interactive elements
- Keyboard navigation supported
- Screen reader compatible
See for full guidelines.
references/accessibility-checklist.mdundefined- 所有组件符合WCAG 2.1 AA标准
- 所有交互元素均有焦点指示器
- 支持键盘导航
- 兼容屏幕阅读器
完整指南请参考。
references/accessibility-checklist.mdundefinedConfiguration Options
配置选项
Theme Presets
主题预设
Zinc (default) - Cool, neutral gray tones:
css
--primary: 240 5.9% 10%;
--muted: 240 4.8% 95.9%;Slate - Slightly cooler, tech-focused:
css
--primary: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;Neutral - True neutral grays:
css
--primary: 0 0% 9%;
--muted: 0 0% 96.1%;Customize further by editing and blocks.
app/globals.css:root.darkZinc(默认) - 冷色调中性灰色:
css
--primary: 240 5.9% 10%;
--muted: 240 4.8% 95.9%;Slate - 偏冷的科技风色调:
css
--primary: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;Neutral - 纯正中性灰色:
css
--primary: 0 0% 9%;
--muted: 0 0% 96.1%;可通过编辑中的和块进一步定制。
app/globals.css:root.darkTailwind v4 Considerations
Tailwind v4注意事项
Check Tailwind version before setup:
bash
npm view tailwindcss versionIf v4.0.0+ is available:
- Use v4 configuration format (directive)
@theme - Consult
references/tailwind-v4-migration.md
If v4 not available (current default):
- Use v3 with forward-compatible CSS variables
- Add comments in generated files:
// TODO: Upgrade to Tailwind v4 when stable
配置前检查Tailwind版本:
bash
npm view tailwindcss version若v4.0.0+可用:
- 使用v4配置格式(指令)
@theme - 参考
references/tailwind-v4-migration.md
若v4不可用(当前默认):
- 使用v3版本并采用向前兼容的CSS变量
- 在生成的文件中添加注释:
// TODO: 稳定后升级到Tailwind v4
Sidebar Layout Options
侧边栏布局选项
If :
sidebarLayout = true- Uses component with responsive sidebar
AppShell - Mobile: Hamburger menu → (slide-over)
Sheet - Desktop: Fixed sidebar with navigation items
If :
sidebarLayout = false- Simple header + content layout
- Header contains site title + actions (mode toggle)
Users can customize navigation in layout files by passing prop:
navigationtsx
<AppShell
navigation={[
{ title: 'Home', href: '/', icon: Home },
{ title: 'About', href: '/about', icon: Info },
]}
siteTitle="My App"
>
{children}
</AppShell>若:
sidebarLayout = true- 使用组件和响应式侧边栏
AppShell - 移动端:汉堡菜单 → (滑入式)
Sheet - 桌面端:固定侧边栏带导航项
若:
sidebarLayout = false- 简单的头部+内容布局
- 头部包含站点标题+操作按钮(模式切换)
用户可通过传递属性在布局文件中自定义导航:
navigationtsx
<AppShell
navigation={[
{ title: 'Home', href: '/', icon: Home },
{ title: 'About', href: '/about', icon: Info },
]}
siteTitle="My App"
>
{children}
</AppShell>Troubleshooting
故障排除
Issue: npm install fails
问题:npm install失败
Cause: Network issues, registry timeout, or package conflicts
Solution:
bash
undefined原因:网络问题、注册表超时或包冲突
解决方案:
bash
undefinedClear npm cache
清除npm缓存
npm cache clean --force
npm cache clean --force
Retry with verbose logging
启用详细日志重试
npm install --verbose
npm install --verbose
Or use specific registry
或使用指定注册表
npm install --registry https://registry.npmjs.org/
undefinednpm install --registry https://registry.npmjs.org/
undefinedIssue: TypeScript errors in components
问题:组件中出现TypeScript错误
Cause: Missing type definitions or tsconfig issues
Solution:
bash
undefined原因:缺失类型定义或tsconfig配置问题
解决方案:
bash
undefinedInstall missing types
安装缺失的类型
npm install --save-dev @types/react @types/react-dom @types/node
npm install --save-dev @types/react @types/react-dom @types/node
Check tsconfig.json paths
检查tsconfig.json路径
{
"compilerOptions": {
"paths": {
"@/": ["./"]
}
}
}
undefined{
"compilerOptions": {
"paths": {
"@/": ["./"]
}
}
}
undefinedIssue: Dark mode not working
问题:暗色模式不生效
Cause: ThemeProvider not wrapping content, or missing
suppressHydrationWarningSolution:
- Verify in layout
<html suppressHydrationWarning> - Ensure wraps
ThemeProvider{children} - Check has
tailwind.config.tsdarkMode: 'class'
原因:ThemeProvider未包裹内容,或缺失
suppressHydrationWarning解决方案:
- 验证布局中的
<html suppressHydrationWarning> - 确保包裹了
ThemeProvider{children} - 检查中是否有
tailwind.config.tsdarkMode: 'class'
Issue: shadcn components not found
问题:找不到shadcn组件
Cause: misconfigured or components not installed
components.jsonSolution:
bash
undefined原因:配置错误或组件未安装
components.json解决方案:
bash
undefinedReinitialize shadcn/ui
重新初始化shadcn/ui
npx shadcn-ui@latest init
npx shadcn-ui@latest init
Re-add components
重新添加组件
npx shadcn-ui@latest add button card input
undefinednpx shadcn-ui@latest add button card input
undefinedIssue: Focus styles not visible
问题:焦点样式不可见
Cause: Global CSS focus styles not applied
Solution:
- Verify includes focus styles layer
app/globals.css - Check rule is present
*:focus-visible - Ensure CSS variable is defined
--ring
原因:全局CSS焦点样式未应用
解决方案:
- 验证包含焦点样式层
app/globals.css - 检查规则是否存在
*:focus-visible - 确保CSS变量已定义
--ring
Resources
资源
This skill bundles comprehensive resources for reference:
本技能包含全面的参考资源:
References (Loaded as Needed)
参考文档(按需加载)
- : Tailwind v3 vs v4 differences, migration guide
tailwind-v4-migration.md - : Complete shadcn/ui component catalog with usage examples
shadcn-component-list.md - accessibility-checklist.md: WCAG 2.1 AA compliance checklist, best practices
- : Design token system, color customization guide
theme-tokens.md
To read a reference:
bash
undefined- :Tailwind v3与v4的差异、迁移指南
tailwind-v4-migration.md - :完整的shadcn/ui组件目录及使用示例
shadcn-component-list.md - accessibility-checklist.md:WCAG 2.1 AA合规检查清单、最佳实践
- :设计令牌系统、颜色定制指南
theme-tokens.md
查看参考文档:
bash
undefinedFrom skill directory
从技能目录执行
cat references/theme-tokens.md
undefinedcat references/theme-tokens.md
undefinedScripts (Executable)
可执行脚本
- : Main automation script for dependency installation and configuration
setup_tailwind_shadcn.py
Execute directly:
bash
python scripts/setup_tailwind_shadcn.py- :用于依赖安装和配置的主自动化脚本
setup_tailwind_shadcn.py
直接执行:
bash
python scripts/setup_tailwind_shadcn.pyAssets (Templates for Output)
资源模板(用于输出)
- Config templates: ,
tailwind.config.ts.template,postcss.config.js.templateglobals.css.template - Component templates: ,
theme-provider.tsx,mode-toggle.tsxapp-shell.tsx - Utility templates:
lib/utils.ts - Page templates: ,
app/layout.tsx.templateapp/page.tsx.template - Example pages: ,
app/examples/forms/,app/examples/dialogs/app/examples/theme/
Copy and customize as needed for the target project.
- 配置模板:、
tailwind.config.ts.template、postcss.config.js.templateglobals.css.template - 组件模板:、
theme-provider.tsx、mode-toggle.tsxapp-shell.tsx - 工具模板:
lib/utils.ts - 页面模板:、
app/layout.tsx.templateapp/page.tsx.template - 示例页面:、
app/examples/forms/、app/examples/dialogs/app/examples/theme/
可按需复制并定制以适配目标项目。
Best Practices
最佳实践
1. Always Test Both Themes
1. 始终测试两种主题
After setup, manually toggle dark mode and verify:
- Color contrast ratios meet WCAG standards
- All text remains readable
- Focus indicators are visible
- Components render correctly
配置完成后,手动切换暗色模式并验证:
- 颜色对比度符合WCAG标准
- 所有文本保持可读
- 焦点指示器可见
- 组件渲染正常
2. Use Semantic Tokens
2. 使用语义化令牌
tsx
[OK] Good (semantic)
<div className="bg-primary text-primary-foreground">
[ERROR] Bad (hard-coded)
<div className="bg-blue-600 text-white">tsx
[正确] 良好(语义化)
<div className="bg-primary text-primary-foreground">
[错误] 不佳(硬编码)
<div className="bg-blue-600 text-white">3. Maintain Type Safety
3. 保持类型安全
Use TypeScript for all components:
tsx
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'default' | 'destructive' | 'outline'
}所有组件使用TypeScript:
tsx
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'default' | 'destructive' | 'outline'
}4. Keep Accessibility in Mind
4. 重视无障碍访问
- Always pair labels with inputs
- Provide for icon-only buttons
aria-label - Test keyboard navigation
- Use semantic HTML
- 始终为输入框配对标签
- 纯图标按钮提供
aria-label - 测试键盘导航
- 使用语义化HTML
5. Document Customizations
5. 记录定制内容
When customizing tokens or components, document changes in project README or inline comments.
定制令牌或组件时,在项目README或内联注释中记录更改。
Post-Setup Tasks
配置后任务
After running this skill, recommend users:
-
Customize brand colors
- Edit in
--primaryapp/globals.css - Test contrast ratios
- Edit
-
Add more components
- Run as needed
npx shadcn-ui add [component] - See for options
references/shadcn-component-list.md
- Run
-
Configure responsive breakpoints
- Adjust Tailwind in
screensif neededtailwind.config.ts
- Adjust Tailwind
-
Set up linting
- Install for accessibility linting
eslint-plugin-jsx-a11y - Add Prettier + Tailwind plugin for formatting
- Install
-
Test production buildbash
npm run build npm start
运行本技能后,建议用户执行以下操作:
-
定制品牌颜色
- 编辑中的
app/globals.css--primary - 测试对比度
- 编辑
-
添加更多组件
- 根据需要运行
npx shadcn-ui add [component] - 查看获取选项
references/shadcn-component-list.md
- 根据需要运行
-
配置响应式断点
- 若需要,调整中的Tailwind
tailwind.config.tsscreens
- 若需要,调整
-
设置代码检查
- 安装用于无障碍检查
eslint-plugin-jsx-a11y - 添加Prettier + Tailwind插件用于格式化
- 安装
-
测试生产构建bash
npm run build npm start
Summary
总结
This skill provides a complete, production-ready Tailwind CSS + shadcn/ui setup for Next.js 16 App Router projects. It handles:
[OK] Dependency installation (Tailwind, shadcn/ui, next-themes)
[OK] Configuration (Tailwind config, PostCSS, global CSS)
[OK] Dark mode setup (ThemeProvider, toggle component)
[OK] Base layout (responsive header, optional sidebar)
[OK] Design tokens (semantic CSS variables)
[OK] Accessibility (WCAG 2.1 AA, keyboard nav, screen readers)
[OK] Example pages (forms, dialogs, theme showcase)
[OK] Documentation (README updates, customization guides)
The setup is forward-compatible with Tailwind v4 and follows official Anthropic skill best practices.
本技能为Next.js 16 App Router项目提供完整的、生产就绪的Tailwind CSS + shadcn/ui配置。涵盖以下内容:
[完成] 依赖安装(Tailwind、shadcn/ui、next-themes)
[完成] 配置(Tailwind配置、PostCSS、全局CSS)
[完成] 暗色模式配置(ThemeProvider、切换组件)
[完成] 基础布局(响应式头部、可选侧边栏)
[完成] 设计令牌(语义化CSS变量)
[完成] 无障碍访问(WCAG 2.1 AA、键盘导航、屏幕阅读器)
[完成] 示例页面(表单、对话框、主题展示)
[完成] 文档(README更新、定制指南)
该配置向前兼容Tailwind v4,并遵循官方Anthropic技能最佳实践。