简介
前言
不知道大家是否使用过 shadcn/ui 它在Github 上拥有了 58k star
它与大多数 UI 组件库(如 Ant desgin 和 Chakra UI)不同,一般组件库都是通过 npm 的方式给项目使用,代码都是存在 node_modules 中; 而 Shadcn UI 可以将单个 UI 组件的源代码下载到项目源代码中(src 目录下),开发者可以自由的修改和使用想要的 UI 组件.
它已经被一些知名的网站(vercel.com、bestofjs.org)等使用。那么它到底有什么优势呢? 一起来来探讨下。
Shadcn UI 简介
Shadcn UI 实际上并不是组件库或 UI 框架。相反,它是可以根据文档“让我们复制并粘贴到应用程序中的可复用组件的集合”。它是由 vercel 的工程师Shadcn创建的,他还创建了一些知名的开源项目,如 Taxonomy,Next.js for Drupal和Reflexjs。 Radix UI - 是一个无头 UI 库。也就是说,它有组件 API,但没有样式。Shadcn UI 建立在 Tailwind CSS 和 Radix UI 之上,目前支持 Next.js、Gatsby、Remix、Astro、Laravel 和 Vite,并且拥有与其他项目快速集成的能力
环境搭建
以nextjs为例:
创建标准的nextjs项目(要支持tailwind.css)
run the cli, 初始化
components.json
npx shadcn-ui@latest init
Which style would you like to use? › Default
Which color would you like to use as base color? › Slate
Do you want to use CSS variables for colors? › no / yes
- 使用: 以
<Button/>
和<Checkbox/>
组件为例:
npx shadcn-ui@latest add button
npx shadcn-ui@latest add checkbox
- page.tsx
浏览器下的效果:
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
export default function Home() {
return (
<div>
<Button>Click me</Button>
<CheckboxDemo />
</div>
)
}
function CheckboxDemo() {
return (
<div className="flex items-center space-x-2">
<Checkbox id="terms" />
<label
htmlFor="terms"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Accept terms and conditions
</label>
</div>
)
}