【React】React + Tailwind CSS 快速入门指南

Tailwind CSS 是一个功能强大实用优先的 CSS 原子性的库,可以帮助你快速构建现代化的用户界面。

它支持的种类框架也非常的多! 例如: ViteNext.js 等...

这个库给我们带来的好处就是可以给我们衍生出其他增强的体验!

比如说 shadcn/uidaisyUI 无样式 UI 库!这些 UI 库就是基于 Tailwind CSS 适配开发的!

参考: tailwindcss 官网

以下是安装和使用 Tailwind CSS 的步骤:

1.创建一个 React 项目

bash 复制代码
npm create vite@latest my-project -- --template react

cd my-project

2.安装 Tailwind CSS

2.1 首先,你需要在项目中安装 tailwindcss及其对等依赖 !

bash 复制代码
// 1.安装 Tailwind CSS
npm install -D tailwindcss@3.4.17

// 2.安装对等依赖 
npm install -D postcss autoprefixer

ps: 安装时我们要指定版本安装 与官网文档版本保持一致即可! 如果不指定版本、默认安装是就是 v4 版本的 tailwindcss

当你继续执行 npx tailwindcss init 就会报错, 没有可执行文件的信息!

bash 复制代码
PS D:\lx\project\emoji-picker> npx tailwindcss init
npm ERR! could not determine executable to run

npm ERR! A complete log of this run can be found in: C:\Users\AppData\Local\npm-cache\_logs\2025-03-08T04_37_23_510Z-debug-0.log

解决方式: 我们安装切换官网的版本下载安装即可解决。

bash 复制代码
npm install -D tailwindcss@3.4.17

3. 初始化 Tailwind CSS 配置文件

3.1 安装完成后,你可以通过以下命令生成 tailwind.config.jspostcss.config.js 配置文件:

因为要分析我们的代码, 把 Tailwind CSS的代码指令, 编译成浏览器可以识别的 CSS。

bash 复制代码
npx tailwindcss init -p

3.2 将这些路径添加到 tailwind.config.js 文件中的所有模板文件中。

tailwind.config.js 文件允许你自定义 Tailwind 的默认配置,例如颜色、字体、间距等。

js 复制代码
/** @type {import('tailwindcss').Config} */
export default {
 // 指定项目目录下那些文件需要处理! 
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

4. 创建 Tailwind CSS 入口文件

在你的项目中入口 CSS 文中引入 Tailwind 的基础样式、组件和工具类:
例如: src/index.css

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

ps: 且必须在你的项目入口 main.js 文件中将 index.css 文件引入到全局。

5. 在你的页面代码中使用 Tailwind CSS

tsx 复制代码
function App() {
  const [count, setCount] = useState(0)

  return (
    <>
      <button className='text-pink-400 px-2 py-2 bg-slate-600 rounded'> Hello World </button>
    </>
  )
}

export default App

6. Vs CodeTailwind CSS 扩展插件

直接在 扩展商店直接安装下载即可。 它可以触发 Tailwind CSS 提示片段。

bash 复制代码
Tailwind CSS IntelliSense

7.总结

  • 一个好的扩展包,一个好的框架也好 ! 往往是因为它的产生,而影响起来的生态!让咱们可以加快开发速度!
  • 如果你有更多问题,欢迎随时问我!😊
相关推荐
cll_86924189115 小时前
WordPress Single Post 文章页美化:响应式表格、图片优化与自动悬浮 Table of Contents(CSS + JS)
前端·css
愛芳芳16 小时前
基于 Electron + Vue3 的仿 PC 微信客户端项目实战
前端·javascript·css·elementui·typescript·electron·vue
用户2986985301417 小时前
前端如何把 TXT 文本文件转成 Word 文档:React 实践
前端·javascript·react.js
赵钰老师18 小时前
基于ArcGIS Pro、R、INVEST等多技术融合下生态系统服务权衡与协同动态分析
python·arcgis·数据分析·r语言
feixing_fx18 小时前
伪类与伪元素的魔法:纯 CSS 打造炫酷的按钮悬停特效
前端·css·css3
moMo1 天前
React Hooks 与闭包
前端·react.js
张明君644511 天前
接口返回 6 条,页面却有 7 篇:从源码看 React 和 Vue 的重复 key
react.js
师傅别念了1 天前
React Hooks 踩坑合集,全是血泪教训
react.js
Peter-Code2 天前
微前端避坑指南:主应用与子应用的高度及滚动条协调
css·前端框架·微前端