Vite
为 Vite 安装并配置 shadcn/ui。
注意:以下指南适用于 Tailwind v4。如果你使用的是 Tailwind v3,请使用 shadcn@2.3.0
。
¥Note: The following guide is for Tailwind v4. If you are using Tailwind
v3, use shadcn@2.3.0
.
创建项目
¥Create project
首先使用 vite
创建一个新的 React 项目。选择 React + TypeScript 模板:
¥Start by creating a new React project using vite
. Select the React + TypeScript template:
pnpm create vite@latest
添加 Tailwind CSS
¥Add Tailwind CSS
pnpm add tailwindcss @tailwindcss/vite
将 src/index.css
中的所有内容替换为以下内容:
¥Replace everything in src/index.css
with the following:
@import "tailwindcss";
编辑 tsconfig.json 文件
¥Edit tsconfig.json file
当前版本的 Vite 将 TypeScript 配置分为三个文件,其中两个需要编辑。将 baseUrl
和 paths
属性添加到 tsconfig.json
和 tsconfig.app.json
文件的 compilerOptions
部分:
¥The current version of Vite splits TypeScript configuration into three files, two of which need to be edited.
Add the baseUrl
and paths
properties to the compilerOptions
section of the tsconfig.json
and
tsconfig.app.json
files:
{
"files": [],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.node.json"
}
],
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
编辑 tsconfig.app.json 文件
¥Edit tsconfig.app.json file
将以下代码添加到 tsconfig.app.json
文件中以解析路径,供你的 IDE 使用:
¥Add the following code to the tsconfig.app.json
file to resolve paths, for your IDE:
{
"compilerOptions": {
// ...
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
]
}
// ...
}
}
更新 vite.config.ts
¥Update vite.config.ts
将以下代码添加到 vite.config.ts,以便你的应用可以解析路径而不会出现错误:
¥Add the following code to the vite.config.ts so your app can resolve paths without error:
pnpm add -D @types/node
import path from "path"
import tailwindcss from "@tailwindcss/vite"
import react from "@vitejs/plugin-react"
import { defineConfig } from "vite"
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
})
运行 CLI
¥Run the CLI
运行 shadcn
init 命令来设置你的项目:
¥Run the shadcn
init command to setup your project:
pnpm dlx shadcn@latest init
你将被问到几个问题来配置 components.json
。
¥You will be asked a few questions to configure components.json
.
Which color would you like to use as base color? › Neutral
添加组件
¥Add Components
你现在可以开始向你的项目添加组件。
¥You can now start adding components to your project.
pnpm dlx shadcn@latest add button
上面的命令将把 Button
组件添加到你的项目中。然后你可以像这样导入它:
¥The command above will add the Button
component to your project. You can then import it like this:
import { Button } from "@/components/ui/button"
function App() {
return (
<div className="flex flex-col items-center justify-center min-h-svh">
<Button>Click me</Button>
</div>
)
}
export default App