第 2 篇:搭建地基------Vue3 + Vite + Tailwind v4 + shadcn-vue
本篇目标
从零跑起一个带 shadcn-vue 的 Vue 3 工程,后续所有篇目都基于它。
所有命令基于 shadcn-vue 官方 Vite 安装文档核实,可照抄。
0. 环境检查
bash
node -v # 需要 18+(推荐 20+)
pnpm -v # 没有就:npm i -g pnpm
1. 创建 Vue3 + TS 工程
bash
pnpm create vite@latest my-ui-kit --template vue-ts
cd my-ui-kit
pnpm install
2. 安装 Tailwind CSS v4
shadcn-vue 当前推荐 Tailwind v4(@tailwindcss/vite 插件方式):
bash
pnpm add tailwindcss @tailwindcss/vite
把 src/style.css 整体替换为:
css
@import "tailwindcss";
3. 配置 Vite 与路径别名
vite.config.ts:
ts
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
plugins: [vue(), tailwindcss()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
})
tsconfig.json (在 compilerOptions 里加):
json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
注意:
tsconfig.json里若有"include": ["src/**/*.ts", ...],保持原样即可。若使用了
tsconfig.app.json,把 paths 加进对应的 app 配置,否则编辑器会标红。
4. 初始化 shadcn-vue
bash
pnpm dlx shadcn-vue@latest init
按提示选择默认值(base color 随意,主题后面可改)。它会:
- 生成
components.json(组件配置) - 生成
src/components/ui目录(组件源码都在这,可自由改) - 在
src/style.css追加设计变量(--background、--primary等)和.dark主题变量
5. 添加本系列要用的组件
bash
pnpm dlx shadcn-vue@latest add input textarea select radio-group checkbox switch label button card
组件以源码形式复制进
src/components/ui/,不是 npm 包依赖------这正是 shadcn 系「源码归你、可自由改」的模型。后面第 6 篇的渲染器会用到这些组件,缺哪个补哪个即可。
6. 验证:能跑起来看到官方 Button
改 src/App.vue:
vue
<script setup lang="ts">
import { Button } from '@/components/ui/button'
</script>
<template>
<div class="flex min-h-screen items-center justify-center">
<Button>my-ui-kit 跑通了</Button>
</div>
</template>
bash
pnpm dev
浏览器打开终端提示的地址,看到带主题色的按钮即成功。
7. 目录结构说明(后面会用到)
src/
├─ style.css # @import "tailwindcss" + 设计变量(第 3 篇)
├─ components/
│ ├─ ui/ # shadcn-vue 组件源码(第 4~6 篇用)
│ ├─ layout/ # 第 4 篇的布局骨架,自己建
│ └─ form/ # 第 6 篇的 SchemaForm,自己建
├─ lib/utils.ts # shadcn-vue 自带的 cn() 工具
└─ pages/ # 第 8 篇的页面 + schema 文件,自己建
8. 常见问题
| 症状 | 原因与解决 |
|---|---|
| 按钮没样式 / 类名不生效 | style.css 没写成 @import "tailwindcss";,或 vite 插件没加 |
编辑器导入 @/... 标红 |
tsconfig.json 的 paths 没配或配错文件 |
shadcn-vue init 报别名错误 |
先确认 vite.config.ts 的 @ 别名已配置,再跑 init |
| 想用 npm/yarn | 命令把 pnpm 换成 npm/npx、yarn/dlxyarn 对应形式即可 |
本篇小结
你已经有了一块可扩展的固定层地基。下一层是「统一样式的来源」------