Vue 3 项目安装 Tailwind CSS 完整步骤(基于 Vite)
1. 创建 Vue 3 项目(可选)
若尚未创建项目,可先初始化一个 Vite 项目:
npm create vite@latest my-vue-app -- --template vue
cd my-vue-app
2. 安装依赖
安装 Tailwind CSS 及其相关依赖:
npm install -D tailwindcss postcss autoprefixer
3. 初始化配置文件
生成 tailwind.config.js
和 postcss.config.js
:
npx tailwindcss init -p
4. 配置模板路径
修改 tailwind.config.js
,确保 content
字段包含所有 Vue 文件路径:
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{vue,js,ts,jsx,tsx}", // 匹配所有 Vue/JS/TS 文件
],
theme: {
extend: {},
},
plugins: [],
}
5. 创建并引入样式文件
- 在
src
目录下新建style.css
文件,并添加 Tailwind 指令:
/* src/style.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
- 在
main.js
中引入样式文件:
import './style.css' // 使用相对路径,避免别名配置问题
6. 运行项目
启动开发服务器:
npm run dev
7. 验证安装
在 App.vue
中添加测试代码:
<template>
<h1 class="text-3xl font-bold underline text-blue-500">
Hello Tailwind CSS!
</h1>
</template>
预期效果:显示蓝色、加粗、带下划线的超大文本。
常见问题
-
样式未生效
- 检查
tailwind.config.js
中content
路径是否正确 - 确保
style.css
已正确引入到main.js
- 检查
-
PostCSS 兼容性问题
确保postcss.config.js
已自动生成,若项目中有自定义 PostCSS 配置,需手动合并。