Tailwind CSS - 內容配置



Tailwind CSS 內容配置指定了專案的原始檔。'tailwind.config.js' 檔案的 Content 部分指定了所有 HTML 模板、Javascript 元件以及包含 Tailwind 類名的任何其他原始檔。

Tailwind CSS config.js

內容源路徑配置

'tailwind.config.js' 檔案的 content 部分中的源路徑配置有助於 Tailwind CSS 掃描所有 HTML、Javascript 元件以及任何包含類名的檔案,以生成這些樣式的相應 CSS。

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

關鍵點

在 Tailwind CSS 中配置內容時需要記住的關鍵點。

  • 使用萬用字元模式(**/*)遞迴匹配檔案。
  • 使用{}和逗號分隔的值來匹配選項列表,例如 {html,js}。
  • 保持路徑相對於專案根目錄。

內容配置模式技巧

為了有效地配置內容,請遵循以下技巧

  • 精確:排除捕獲不必要檔案或目錄(例如 node_modules)的廣泛模式。
  • content: [
    './components/**/*.{html,js}',
    './pages/**/*.{html,js}',
    './index.html',  // Include specific files if needed
    ],
        
  • 包含入口點:確保您的 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>
        
  • 始終將 props 對映到靜態類名,而不是使用 props 來動態構建類。
  • 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: '<div class="font-bold">', 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)/,
    },
  ],
  // ...
}

您可以強制 Tailwind 為某些類建立額外的樣式,方法是將它們新增到 'variants' 選項中。

/** @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 不支援動態類名構建。
  • <!-- Incorrect -->
    <div class="text-{{ error ? 'red' : 'green' }}-600"></div>
    
    <!-- Correct -->
    <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",
        },
    }
        
廣告