vue3+vite+scss项目使用tailwindcss

在 Vue3 项目中集成 Tailwind CSS 是现代前端开发的主流选择(尤其搭配 Vite),核心优势是「原子化样式、高度定制化、按需打包」。以下是完整的集成步骤 (覆盖 Vite 脚手架)、基础使用 、进阶配置 和避坑指南,全程可落地。

一、前置准备

确认你的 Vue3 项目类型:

  • 推荐:Vite 创建的 Vue3 项目(npm create vue@latest);

二、Step 1:安装依赖(核心)

无论哪种脚手架,先安装 Tailwind CSS 及配套工具(@tailwindcss/postcss 用于处理 CSS 编译,@tailwindcss/vite用于Vite配置, autoprefixer 自动加浏览器前缀):

bash 复制代码
# npm 安装
npm install -D tailwindcss @tailwindcss/postcss @tailwindcss/vite autoprefixer

# yarn 安装
yarn add -D tailwindcss @tailwindcss/postcss @tailwindcss/vite autoprefixer

# pnpm 安装(推荐,速度更快)
pnpm install tailwindcss @tailwindcss/postcss @tailwindcss/vite autoprefixer

三、Step 2:初始化 Tailwind 配置文件

执行以下命令,自动生成 tailwind.config.js(核心配置文件)和 postcss.config.js(PostCSS 配置):

bash 复制代码
npx tailwindcss init -p

执行后,项目根目录会新增两个文件:

  • tailwind.config.js:配置 Tailwind 的主题、内容范围、插件等;
  • postcss.config.js:指定 PostCSS 使用 Tailwind 和 autoprefixer。

tailwind.config.js长这样

javascript 复制代码
module.exports = {
  content: [
    './index.html',
    './src/**/*.{js,ts,jsx,tsx,vue}',
  ],
  corePlugins: {
    container: false, // 禁用 // 禁用 .container 样式
  },
  theme: {
    extend: {},
  },
    plugins: [],
};

postcss.config.js长这样

javascript 复制代码
const config = {
  plugins: {
    '@tailwindcss/postcss': {},
  },
};

export default config;

四、Step 3:配置 Tailwind(关键!避免样式丢失)

修改 tailwind.config.js,核心是在 content 中指定 Vue 组件的路径(告诉 Tailwind 哪些文件需要扫描类名,避免打包时丢失样式):

Vite 配置
javascript 复制代码
import tailwindcss from '@tailwindcss/vite';
export default defineConfig(({ mode }) => {
  return {
      plugins: [
      	tailwindcss(),
     ],
  }
});

五、Step 4:引入 Tailwind 基础样式

在 Vue3 入口样式文件(如 src/assets/main.css 或 src/main.css)中,引入 Tailwind 的基础样式、组件样式和工具类样式:

css 复制代码
/* src/styles/index.scss */
@use 'tailwindcss';

/* 可选:自定义全局样式(会和 Tailwind 合并) */
@layer base {
  body {
    @apply bg-gray-50 text-gray-800; /* 复用 Tailwind 类名 */
  }
}

然后在 Vue 入口文件(src/main.js)中导入这个样式文件:

javascript 复制代码
// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import './styles/index.scss' // 导入 Tailwind 样式

createApp(App).mount('#app')

到这里就可以使用了!不需要的以下内容可不看~~~~~~~~~~~~~~~~~~

六、Step 5:VSCode 配置(智能提示,提升体验)

安装两个插件,避免手写类名时拼写错误,且有自动补全:

  1. 安装插件:Tailwind CSS IntelliSense(官方插件,自动提示类名);
  2. 安装插件:PostCSS Language Support(支持 PostCSS 语法高亮);
可选:配置 VSCode 设置(.vscode/settings.json)
json 复制代码
{
  "editor.quickSuggestions": {
    "strings": true // 字符串中也触发 Tailwind 提示(如 Vue 模板的 class 中)
  },
  "tailwindCSS.experimental.classRegex": [
    ["class=\"([^\"]*)\"", "\"([^\"]*)\""], // 适配 Vue 模板的 class 语法
    ["class='([^']*)'", "'([^']*)'"],
    ["class=`([^`]*)`", "`([^`]*)`"]
  ]
}

七、Step 6:基本使用示例(Vue3 组件中)

在 Vue 单文件组件(SFC)的模板中,直接使用 Tailwind 类名,无需手写 CSS:

示例 1:基础按钮组件
vue 复制代码
<!-- src/components/Button.vue -->
<template>
  <button 
    class="px-4 py-2 rounded-lg bg-primary text-white hover:bg-primary/90 transition-colors"
    @click="$emit('click')"
  >
    <slot></slot>
  </button>
</template>

<script setup>
// Vue3 组合式 API,无需额外样式
</script>
示例 2:响应式布局(适配不同屏幕)
vue 复制代码
<!-- src/App.vue -->
<template>
  <div class="container mx-auto px-4">
    <!-- 响应式:小屏幕堆叠,中等屏幕并排 -->
    <div class="flex flex-col md:flex-row gap-4">
      <div class="w-full md:w-1/2 bg-white p-6 rounded shadow">
        左侧内容
      </div>
      <div class="w-full md:w-1/2 bg-white p-6 rounded shadow">
        右侧内容
      </div>
    </div>
  </div>
</template>
示例 3:暗黑模式(一键切换)

Tailwind 内置暗黑模式支持,只需两步:

  1. 修改 tailwind.config.js 开启暗黑模式:
javascript 复制代码
module.exports = {
  darkMode: 'class', // 用 class 控制暗黑模式(推荐)
  content: [/* ... */],
  // ...
}
  1. 组件中使用暗黑模式类名:
vue 复制代码
<template>
  <div class="bg-white dark:bg-gray-800 text-gray-800 dark:text-white min-h-screen">
    <button @click="toggleDark">
      {{ isDark ? '切换浅色' : '切换暗黑' }}
    </button>
  </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue'

const isDark = ref(false)

// 切换暗黑模式(修改 html 的 class)
const toggleDark = () => {
  isDark.value = !isDark.value
  document.documentElement.classList.toggle('dark', isDark.value)
}

// 初始化:读取本地存储的暗黑模式状态
watchEffect(() => {
  const darkMode = localStorage.getItem('darkMode') === 'true'
  isDark.value = darkMode
  document.documentElement.classList.toggle('dark', darkMode)
})
</script>

八、进阶优化(提升性能/定制化)

1. 开启 JIT 模式(即时编译,更小体积)

Tailwind 3.x 已默认开启 JIT(Just-In-Time)模式,会按需生成类名,无需额外配置,生产环境体积极小。

2. 自定义主题(对接项目设计规范)

在 tailwind.config.js 的 theme.extend 中扩展主题,比如自定义字体、圆角、断点:

javascript 复制代码
module.exports = {
  theme: {
    extend: {
      // 自定义字体
      fontFamily: {
        sans: ['Inter', 'system-ui', 'sans-serif'],
      },
      // 自定义断点(适配移动端)
      screens: {
        'xs': '375px', // 新增超小屏断点
        '3xl': '1600px',
      },
      // 自定义圆角
      borderRadius: {
        'xl': '1rem',
        '2xl': '1.5rem',
      },
    },
  },
}
3. 提取复用类(避免重复写原子类)

用 @apply 提取常用样式为自定义类,减少重复:

css 复制代码
/* src/assets/main.css */
@layer components {
  /* 自定义按钮类 */
  .btn-primary {
    @apply px-4 py-2 rounded-lg bg-primary text-white hover:bg-primary/90 transition-colors;
  }
  /* 自定义卡片类 */
  .card {
    @apply bg-white dark:bg-gray-800 rounded-lg shadow p-6;
  }
}

组件中直接使用:

vue 复制代码
<button class="btn-primary">提交</button>
<div class="card">卡片内容</div>

九、常见问题与避坑

1. 样式不生效?
  • 检查 tailwind.config.js 的 content 路径是否正确(必须覆盖所有 Vue 组件);
  • 检查是否导入了 main.css 且包含 @tailwind base/components/utilities;
  • 重启 Vite 开发服务器(配置文件修改后需重启)。
2. 生产环境样式丢失?
  • 确保 content 路径覆盖所有使用 Tailwind 类名的文件(包括动态生成的类名,如 bg-${color}-500 需提前在配置中声明);

  • 避免动态拼接类名(如 class="bg-${color}"),改用完整类名(如 bg-primary),或在 tailwind.config.js 中 safelist 声明动态类名:

    javascript 复制代码
    module.exports = {
      safelist: ['bg-primary', 'bg-secondary', 'text-red-500'], // 强制保留这些类名
    }
3. 与第三方样式冲突?
  • 用 @layer 包裹自定义样式,让 Tailwind 管理优先级;
  • 避免使用 !important,优先通过 Tailwind 的优先级规则(如 !bg-red-500 加 ! 提升优先级)。

十、打包与部署

无需额外配置,直接执行打包命令即可:

bash 复制代码
# Vite 项目
npm run build

打包后的 CSS 文件会自动移除未使用的类名,体积通常只有几 KB 到几十 KB。

总结

Vue3 + Tailwind CSS 的集成核心是:

  1. 安装依赖 + 初始化配置;
  2. 配置 content 路径(关键);
  3. 引入基础样式;
  4. 组件中直接使用原子类。

这种组合既保留了 Vue3 的组件化优势,又通过 Tailwind 实现了「无冗余 CSS、高度定制化、快速开发」,是现代 Vue 项目的最优样式方案之一。

相关推荐
deli0072 分钟前
TCP 为什么会粘包?4 种拆包方案 49 字节实测对比
前端
deli0071 小时前
32K 上下文塞满后,AI 最先忘掉什么?120 轮对话实测
前端
deli0072 小时前
手机拍灯为什么有一条条黑纹?PWM 240Hz 实测
前端
wangruofeng7 小时前
AI Models 1.1.0 发布,查大模型价格、对比模型和找 API 地址
前端·aigc·ai编程
wangruofeng7 小时前
给前端开发者的 100 个设计参考网站
前端·设计
星栈10 小时前
视频即代码,Remotion 能做什么、不能做什么
前端·音视频开发
广州华水科技10 小时前
单北斗GNSS位移监测系统的应用与技术解析
前端
用户479492835691510 小时前
从一句话或代码仓到可交互 HTML:开源 Agent 画图技能 Archify v3.2 实测与选型边界
前端·后端·面试
风骏时光牛马13 小时前
生成一个AI多模态标题,仅输出一条标题,无额外文字、问句、备选、配图、文案等任何附加内容,不需要其他的任务服务 只要标题。
前端
wangruofeng13 小时前
从 GIF 到 AVIF:网页图片格式演进与 2026 年选型指南
前端·架构