你正在瀏覽的是 Tailwind CSS v2. 的技術文件
Tailwind CSS 的 GitHub

在 Gatsby 安裝 Tailwind CSS

在 Gatsby 專案中設定 Tailwind CSS。

建立專案

首先,建立一個新的 Gatsby,如果你還沒有一個已經設定好的專案。 最常見的方式是使用 Gatsby CLI:

gatsby new my-project
cd my-project

設定 Tailwind CSS

Tailwind CSS 需要 Node.js 12.13.0 以上版本。

使用 npm 安裝 Tailwind

使用 npm 安裝 gatsby-plugin-postcss以及Tailwind 和它需要的依賴套件 (peer-dependencies):

npm install -D gatsby-plugin-postcss tailwindcss@latest postcss@latest autoprefixer@latest

建立設定檔案 files

然後產生 tailwind.config.jspostcss.config.js 檔案:

npx tailwindcss init -p

這會在專案的根目錄建立一個基本的 tailwind.config.js 檔案:

// tailwind.config.js
module.exports = {
  purge: [],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

想了解更多關於 Tailwind 的設定可以到 配置文件

這也會同時建立 postcss.config.js 檔案,並包含 tailwindcssautoprefixer 的設定:

// postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}

如果你打算使用別的 PostCSS 插件,你應該要閱讀我們在 using PostCSS as your preprocessor 的文件獲得更完整的資訊,來找出最合適的方式跟 Tailwind 一同運作。

讓 Tailwind 在生產環境建置時移除不必要的樣式

在你的 tailwind.config.js 檔案設定 purge 選項指定路徑到你所有的 pages 和 components,讓 Tailwind 可以在生產環境建置時清除沒有使用的樣式:

  // tailwind.config.js
  module.exports = {
-   purge: [],
+   purge: ['./src/**/*.{js,jsx,ts,tsx}'],
    darkMode: false, // or 'media' or 'class'
    theme: {
      extend: {},
    },
    variants: {
      extend: {},
    },
    plugins: [],
  }

閱讀我們在 優化生產環境 的說明來獲得更多關於 「清除不必要樣式以增進效能」 的資訊。

啟用 gatsby-plugin-postcss

gatsby-config.js 檔案中啟用 postcss 插件

  // gatsby-config.js
  module.exports = {
    /* Your site config here */
-   plugins: [],
+   plugins: ['gatsby-plugin-postcss'],
  }

在你的 CSS 中使用 Tailwind

建立 ./src/styles/global.css 檔案

使用 @tailwind 指令來引用 Tailwind 的 basecomponentsutilities 樣式,並且取代原本檔案的內容:

/* ./src/styles/global.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

Tailwind 會在建置時將這些指令替換成你配置系統時所對應的樣式內容。

閱讀我們的 增加基底樣式提取成元件增加新功能 文件以使用 Tailwind 為你自定義的 CSS 做最好的擴充。

最後,如果 ./gatsby-browser.js 檔案還不存在的話,請在專案的根目錄建立它,然後引用 (import) 你的 CSS 檔案:

  // ./gatsby-browser.js
+ import './src/styles/global.css';

Read the Gatsby documentation on using global styles to learn more about working with global CSS files in Gatsby.


你已經完成了!現在當你執行 gatsby develop,Tailwind CSS 將會在你的 Gatsby 專案中運行。

接著來了解功能優先流程