Vue 2 项目中配置 Tailwind CSS 和 Font Awesome 的最佳实践

Vue 2 项目中配置 Tailwind CSS 和 Font Awesome 的最佳实践

一、Tailwind CSS 配置

1. 安装依赖

bash 复制代码
npm install tailwindcss@npm:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9

2. 创建配置文件

bash 复制代码
npx tailwindcss init

3. 创建样式文件

src/assets/tailwind.css 中添加:

css 复制代码
@tailwind base;
@tailwind components;
@tailwind utilities;

4. 配置 PostCSS

项目根目录创建 postcss.config.js

js 复制代码
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}

5. 引入样式

main.js 中:

js 复制代码
import '@/assets/tailwind.css';

6. 测试配置

App.vue 中添加测试代码:

vue 复制代码
<template>
  <div class="p-4">
    <h1 class="text-2xl font-bold text-blue-500">TailwindCSS 是否生效?</h1>
    <button class="mt-4 px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600">
      测试按钮
    </button>
  </div>
</template>

第二种引入方式基本和第一种相同,不同的是直接引入:

复制代码
import "tailwindcss/tailwind.css"

参考:https://juejin.cn/post/7091578341194465317

二、引入方式的对比

特性 import "tailwindcss/tailwind.css" import '@/assets/css/tailwind.css'
是否可定制 Tailwind ❌ 不可以 ✅ 可以
是否使用 @tailwind 指令 ❌ 不使用 ✅ 使用
是否支持 PurgeCSS/裁剪 ❌ 默认不裁剪 ✅ 支持
是否适合生产环境 ❌ 主要用于 demo ✅ 适合生产环境

推荐 :正式项目使用 @tailwind 指令方式(第二种)

三、Font Awesome 配置(引入 Font Awesome 图标)

方法一:CDN 引入(简单快速)

public/index.html 中添加:

html 复制代码
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" />

使用示例:

html 复制代码
<i class="fa-solid fa-qrcode text-2xl text-primary"></i>

方法二:npm 安装(推荐生产环境)

  1. 安装依赖:
bash 复制代码
npm install @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons @fortawesome/free-brands-svg-icons @fortawesome/vue-fontawesome
  1. main.js 中配置:
js 复制代码
import { library } from '@fortawesome/fontawesome-svg-core'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { faQrcode } from '@fortawesome/free-solid-svg-icons'
import { faWeixin } from '@fortawesome/free-brands-svg-icons'

library.add(faQrcode, faWeixin)
Vue.component('font-awesome-icon', FontAwesomeIcon)
  1. 使用示例:
html 复制代码
<font-awesome-icon :icon="['fas', 'qrcode']" class="text-2xl text-primary" />
<font-awesome-icon :icon="['fab', 'weixin']" class="text-xl" />

四、总结对比

使用方式 优点 缺点
CDN 引入 简单、快速 无法按需加载,文件较大
npm 引入 + 组件方式 可按需加载图标,灵活 需安装和注册,稍复杂

推荐:生产环境使用 npm 安装方式

相关推荐
崔庆才丨静觅6 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60616 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了7 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅7 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅7 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅7 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment8 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅8 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊8 小时前
jwt介绍
前端
爱敲代码的小鱼8 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax