# Tailwind CSS 配置指南

# 1. 安装依赖

首先需要安装必要的依赖包:

yarn add -D tailwindcss postcss autoprefixer
# 或者使用 npm
npm install -D tailwindcss postcss autoprefixer

# 2. 初始化配置文件

生成 Tailwind 和 PostCSS 的配置文件:

npx tailwindcss init -p

这个命令会创建两个文件:

  • tailwind.config.js
  • postcss.config.js

# 3. 配置文件内容

# tailwind.config.js

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
    "./src/**/*.html"
  ],
  theme: {
    extend: {},
  },
  plugins: [],
};

# postcss.config.js

module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
};

# 4. Webpack 配置

如果你使用 Webpack,需要配置相关 loader:

module: {
  rules: [
    {
      test: /\.css$/i,
      include: [
        resolve(__dirname, "src"),
        resolve(__dirname, "node_modules"),
      ],
      use: [
        MiniCssExtractPlugin.loader,
        {
          loader: "css-loader",
          options: { importLoaders: 1 },
        },
        "postcss-loader",
      ],
    },
  ],
},
plugins: [
  new MiniCssExtractPlugin({
    filename: "[name].css",
    chunkFilename: "[id].css",
  }),
],

# 5. 创建和配置 CSS 文件

在 src 目录下创建 index.cssstyles.css,添加 Tailwind 的基础指令:

@tailwind base;
@tailwind components;
@tailwind utilities;

# 6. 引入 CSS

在项目的入口文件(通常是 index.tsxindex.js)中引入 CSS 文件:

import './index.css';  // 或 './styles.css'

# 7. 使用 Tailwind 类

现在你可以在组件中使用 Tailwind 的工具类了:

import React from "react";

const App: React.FC = () => {
  return (
    <div className="container mx-auto">
      <h1 className="text-red-500 text-2xl font-bold">
        Welcome to My App
      </h1>
    </div>
  );
};

export default App;

# 8. Tailwind 常用类名说明

# 色颜

  • 文本颜色:text-{color}-{shade}
    • 例:text-red-500, text-blue-700
  • 背景颜色:bg-{color}-{shade}
    • 例:bg-gray-100, bg-blue-200

# 间距

  • 内边距:p-{size}p{t|r|b|l}-{size}
    • 例:p-4, pt-2
  • 外边距:m-{size}m{t|r|b|l}-{size}
    • 例:m-4, mt-2

# 尺寸

  • 宽度:w-{size}
    • 例:w-full, w-1/2
  • 高度:h-{size}
    • 例:h-screen, h-32

# 弹性布局

  • flex
  • flex-row, flex-col
  • items-center
  • justify-center

# 9. 常见问题排查

如果样式没有生效,检查:

  1. 确认所有依赖都已正确安装
  2. 检查配置文件路径是否正确
  3. 确保 CSS 文件被正确引入
  4. 验证类名是否正确(如 text-red-500 而不是 text-red
  5. 清除缓存并重新构建项目

# 10. 性能优化

  • 在生产环境中使用 PurgeCSS(Tailwind 内置)
  • 配置 content 数组以正确包含所有需要的文件
  • 考虑使用 JIT(即时)模式提高开发体验

# 参考资料