Tailwind CSS 内容配置详解

原创
admin 4个月前 (08-07) 阅读数 18 #CSS

Tailwind CSS 内容配置详解

Tailwind CSS 内容配置指定了项目的源文件。在 'tailwind.config.js' 文件中的 Content 部分指定了所有包含 Tailwind 类名的 HTML 模板、JavaScript 组件和其他源文件。

内容源路径配置

在 'tailwind.config.js' 文件内容部分配置源路径,可以帮助 Tailwind CSS 扫描所有包含类名的 HTML、JavaScript 组件和其他文件,以为这些样式生成相应的 CSS。

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './pages/**/*.{html,js}',
    './components/**/*.{html,js}'
  ],
  // ...
}

关键要点

在配置 Tailwind CSS 内容时需要记住的关键点:

  • 使用 glob 模式 (**/*) 递归匹配文件。

  • 使用 {} 和逗号分隔的值来匹配选项列表,如 {html,js}。

  • 保持路径相对于项目根目录。

内容配置模式技巧

为了有效配置内容,请遵循以下技巧:

  • 精确配置: 排除捕获不必要文件或目录的广泛模式,如 node_modules。

content: [
'./components/**/*.{html,js}',
'./pages/**/*.{html,js}',
'./index.html',  // 如需要,包含特定文件
],
  • 包含入口点: 确保 Tailwind 设置包含主 HTML 文件,通常位于 public/index.html。

  • content: [
    './public/index.html',
    './src/**/*.{html,js}',
    ],
  • JavaScript 文件: 包含任何向 HTML 添加类名的 JS 文件。

  • content: [
    './src/**/*.js',
    ],
  • 排除 CSS 文件: 永远不要在内容配置中包含 CSS 文件。

  • content: [
    './src/**/*.css',
    ],

    深度类识别

    Tailwind 使用正则表达式从源代码中提取潜在的类名,而不解析或执行它。

    <div class="md:flex">
      <div class="md:flex-shrink-0">
        <img class="rounded-lg md:w-56" src="/img/shopping.jpg" alt="Woman paying for a purchase">
      </div>
      <div class="mt-4 md:mt-0 md:ml-6">
        <div class="uppercase tracking-wide text-sm text-indigo-600 font-bold">
          Marketing
        </div>
        <a href="/get-started" class="block mt-1 text-lg leading-tight font-semibold text-gray-900 hover:underline">
          Finding customers for your new business
        </a>
        <p class="mt-2 text-gray-600">
          Getting a new business off the ground is a lot of hard work.
          Here are five ideas you can use to find your first customers.
        </p>
      </div>
    </div>

    注意: Tailwind 可以与任何语言(如 JSX)一起工作,通过搜索所有地方的类名,而不仅仅是 HTML。

    动态类名

    Tailwind 只会在您的代码中找到完整的类名。如果您使用字符串或部分构建类名,Tailwind 将无法识别它们,也不会生成相应的 CSS。

    创建类名时应遵循的措施:

    • 始终使用完整的类名,而不是动态构建类名。

    <div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
  • 映射属性到静态类名: 始终将属性映射到静态类名,而不是使用属性动态构建类。

  • function Button({ color, children }) {
      const colorVariants = {
        blue: "bg-blue-600 hover:bg-blue-500",
        red: "bg-red-600 hover:bg-red-500",
      };
    
      return <button className={`${colorVariants[color]} ...`}>{children}</button>;
    }

    使用外部库

    当使用第三方库并用自己的自定义 CSS 进行样式设计时,尝试不使用 Tailwind 的 @layer 功能编写这些样式。这将使 Tailwind 更容易扫描第三方库的源代码。

    @tailwind base;
    @tailwind components;
    
    .select2-dropdown {
        @apply rounded-b-lg shadow-md;
    }
    .select2-search {
        @apply border border-gray-300 rounded;
    }
    .select2-results__group {
        @apply text-lg font-bold text-gray-900;
    }
    /* ... */
    
    @tailwind utilities;

    如果您在多个项目中使用 Tailwind 样式的组件,请确保已配置 Tailwind 以扫描它们以查找类名。

    module.exports = {
        content: [
            './components/**/*.{html,js}',
            './pages/**/*.{html,js}',
            './node_modules/@my-company/tailwind-components/**/*.js',
        ],
        // ...
        }

    如果您在使用工作区的 monorepo 中,可能需要使用 require.resolve 以便 Tailwind 可以找到您的内容文件。

    const path = require('path');
    
    module.exports = {
        content: [
        './components/**/*.{html,js}',
        './pages/**/*.{html,js}',
        path.join(path.dirname(require.resolve('@my-company/tailwind-components')), '**/*.js'),
        ],
        // ...
    }

    使用相对路径

    Tailwind 默认使用当前目录的路径。为避免问题,将 'relative' 属性设置为 'true',以将路径绑定到 'tailwind.config.js' 文件。

    module.exports = {
      content: {
        relative: true,
        files: ["./pages/**/*.{html,js}", "./components/**/*.{html,js}"],
      },
      // ...
    };

    设置原始内容

    要在 Tailwind 中扫描原始内容而不是文件内容,请使用带有 "raw" 键的对象而不是文件路径。这允许您配置 Tailwind 以扫描自定义内容。

    /** @type {import('tailwindcss').Config} */
    module.exports = {
        content: [
        './pages/**/*.{html,js}',
        './components/**/*.{html,js}',
        { raw: '', extension: 'html' },
        ],
        // ...
    }

    安全列出类

    如果您希望 Tailwind 生成内容文件中不存在的某些类名,请使用 safelist 选项。

    /** @type {import('tailwindcss').Config} */
    module.exports = {
        content: [
        './pages/**/*.{html,js}',
        './components/**/*.{html,js}',
        ],
        safelist: [
        'bg-red-500',
        'text-3xl',
        'lg:text-4xl',
        ]
        // ...
    }

    使用正则表达式

    Tailwind 支持基于模式的安全列出,在需要安全列出许多类的情况下。

    /** @type {import('tailwindcss').Config} */
    module.exports = {
      content: [
        './pages/**/*.{html,js}',
        './components/**/*.{html,js}',
      ],
      safelist: [
        'text-2xl',
        'text-3xl',
        {
          pattern: /bg-(red|green|blue)-(100|200|300)/,
        },
      ],
      // ...
    }

    您可以通过将类添加到 'variants' 选项来强制 Tailwind 为某些类创建额外样式。

    /** @type {import('tailwindcss').Config} */
    module.exports = {
      content: [
        './pages/**/*.{html,js}',
        './components/**/*.{html,js}',
      ],
      safelist: [
        'text-2xl',
        'text-3xl',
        {
          pattern: /bg-(red|green|blue)-(100|200|300)/,
          variants: ['lg', 'hover', 'focus', 'lg:hover'],
        },
      ],
      // ...
    }

    消除类

    Tailwind 可能会创建不必要的类,例如即使未使用也会生成 'container' 类,如下所示。

    <div class="text-lg leading-8 text-gray-600">
      Every custom pool we design starts as a used shipping container, and is
      retrofitted with state of the art technology and finishes to turn it into
      a beautiful and functional way to entertain your guests all summer long.
    </div>

    为了避免与现有 CSS 冲突而不为所有 Tailwind 类添加前缀,请使用 blocklist 选项来忽略特定类。

    /** @type {import('tailwindcss').Config} */
    module.exports = {
        content: [
        './pages/**/*.{html,js}',
        './components/**/*.{html,js}',
        ],
        blocklist: [
        'container',
        'collapse',
        ],
        // ...
    }

    源文件转换

    如果您编写的内容会转换为 HTML(如 Markdown),请在提取类之前先将内容转换为 HTML。使用 'content.transform' 转换文件,并使用 'content.files' 指定源路径。

    const remark = require('remark')
    
    module.exports = {
      content: {
        files: ['./src/**/*.{html,md}'],
        transform: {
          md: (content) => {
            return remark().process(content)
          }
        }
      },
      // ...
    }

    修改提取逻辑

    使用 'extract' 自定义特定文件类型的类名检测。

    注意: 这是一个高级功能,您需要以不同方式指定源路径。

    /** @type {import('tailwindcss').Config} */
    module.exports = {
      content: {
        files: ['./src/**/*.{html,wtf}'],
        extract: {
          wtf: (content) => {
            return content.match(/[^<>"'`\s]*/g)
          }
        }
      },
      // ...
    }

    常见问题排查

    以下是在配置 Tailwind CSS 内容时生成的一些常见问题以及避免它们的措施。

    • 缺少类: 如果 Tailwind 没有生成类,请仔细检查您的内容配置和文件扩展名(例如,React 组件使用 'jsx' 而不是 'js'),以确保它匹配所有源文件。

    module.exports = {
        content: [
            './src/**/*.{html,js}',
            './src/**/*.{html,js,jsx}'
        ],
        // ...
    }
  • 动态类名: Tailwind 不支持动态类名构建。

  • <!-- 错误 -->
    <div class="text-{{ error ? 'red' : 'green' }}-600"></div>
    
    <!-- 正确 -->
    <div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
  • 无限样式重建: 确保您的构建工具正确支持 glob 模式。

  • content: [
    './src/**/*.{html,js}',
    './src/pages/**/*.{html,js}',
    './src/components/**/*.{html,js}',
    './src/index.html',
    ],
  • 输出问题: 它可能不支持 PostCSS,导致问题。尝试使用 Tailwind CLI 单独编译 CSS,避免集成问题。

  • // package.json
    {
        // ...
        "scripts": {
        "start": "concurrently \"npm run start:css\" \"react-scripts start\"",
        "start:css": "tailwindcss -o src/tailwind.css --watch",
        "build": "npm run build:css && react-scripts build",
        "build:css": "NODE_ENV=production tailwindcss -o src/tailwind.css -m",
        },
    }
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权本站发表,未经许可,不得转载。

作者文章
热门
最新文章
标签列表