กลับไปหน้าสูตร
#shadcn#ui#nextjs#tailwind#cli#cheatsheet
Shadcn/UI CLI Cheatsheet
คู่มือฉบับสมบูรณ์ Shadcn/UI CLI: ครอบคลุมการจัดการ Registry, ระบบ Blocks, การทำ Custom Themes และการแก้ปัญหาใน Monorepo
11 มีนาคม 2569อ่านประมาณ 1 นาที
สารบัญสูตร
🚀 Core CLI Operations (Modern npx shadcn)
ใช้ npx shadcn@latest เพื่อรองรับฟีเจอร์ใหม่ล่าสุดเสมอ:
| Command | คำอธิบายขั้นสูง |
|---|---|
init | เริ่มต้นโปรเจกต์ (สร้าง components.json) และติดตั้ง base dependencies |
add [component] | ติดตั้งคอมโพเนนต์ (เช่น button, dialog, sheet) พร้อม dependencies |
add --all | ติดตั้งทุกคอมโพเนนต์ใน Registry (เหมาะสำหรับเริ่มโปรเจกต์ใหญ่) |
add --overwrite | บังคับเขียนทับไฟล์เดิม (ใช้ -o ได้) |
diff [component] | ตรวจสอบโค้ดในเครื่องเทียบกับต้นฉบับ (ช่วยในการทำ Upstream Sync) |
upgrade | อัปเดตคอมโพเนนต์และไฟล์ utils ให้เป็นเวอร์ชันล่าสุด |
🛠 `init` Config & Flags
| Flag | การใช้งาน |
|---|---|
-d, --defaults | ข้ามการตอบคำถาม ใช้ค่ามาตรฐาน (Slate, CSS Vars, New York) |
-y, --yes | ตอบตกลงทุกการยืนยัน (ดีมากสำหรับ automation scripts) |
--style <name> | เลือกสไตล์ระหว่าง default (ดูสะอาด) หรือ new-york (ดูแน่น) |
--base-color <name> | เลือกสีหลัก (เช่น zinc, slate, stone, gray, neutral) |
🧱 Blocks & Templates (New Feature!)
Shadcn รองรับการแอด "Blocks" ซึ่งเป็น Layout สำเร็จรูปขนาดใหญ่:
npx shadcn@latest add sidebar-01: แอด Sidebar สำเร็จรูปที่มี Logic พร้อมใช้npx shadcn@latest add login-01: แอดหน้า Login แบบครบวงจร- Browser Registry: คุณสามารถดู ID ของ Block ได้จากหน้าเว็บ shadcn/ui แล้วสั่งแอดผ่าน CLI ได้ทันที
📄 `components.json` Schema Deep Dive
การตั้งค่าที่ส่งผลต่อการทำงานของ CLI:
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true, // รองรับ React Server Components (Next.js App Router)
"tsx": true, // ใช้ TypeScript (ถ้าเป็น false จะโหลดไฟล์ .js)
"tailwind": {
"config": "tailwind.config.ts",
"css": "app/globals.css",
"baseColor": "slate",
"cssVariables": true, // ใช้สีแบบ --primary แทนคลาสตรงๆ
"prefix": "" // เพิ่ม Prefix ให้คลาส (เช่น tw-button) ป้องกันคลาสชนกัน
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
}
}
🔗 Custom Registry & Remote Components
คุณสามารถแอดคอมโพเนนต์จากแหล่งอื่นที่ไม่ใช่เว็บหลักได้:
- From URL:
npx shadcn@latest add https://example.com/button.json - From GitHub:
npx shadcn@latest add github-user/repo/button - Private Registry: ระบุ
--registry <url>ในคำสั่ง add เพื่อดึงจาก Server ภายในองค์กร
💡 Troubleshooting & Advanced Tips
1) ปัญหา Alias @/ ไม่ทำงาน
หาก CLI แอดไฟล์ผิดที่ ให้เช็ก tsconfig.json ว่ามี paths ตรงกับ components.json หรือไม่:
"paths": {
"@/*": ["./*"]
}
2) การใช้งานใน Monorepo (Turbo/Nx)
ต้องระบุ --cwd (Current Working Directory) เสมอ:
npx shadcn add button --cwd apps/web
3) การล้างสไตล์เดิมแล้วแอดใหม่
หากต้องการเปลี่ยนสีหลักทั้งโปรเจกต์:
- แก้ไข
baseColorในcomponents.json - รัน
npx shadcn initอีกครั้ง (ระบุ-o) เพื่อให้ระบบเจนไฟล์ CSS ใหม่ - รัน
npx shadcn upgradeเพื่ออัปเดตคอมโพเนนต์ทั้งหมดให้ใช้สีใหม่