在 Gatsby 專案中設定 Tailwind CSS。
首先,建立一個新的 Gatsby,如果你還沒有一個已經設定好的專案。 最常見的方式是使用 Gatsby CLI:
gatsby new my-project
cd my-project
Tailwind CSS 需要 Node.js 12.13.0 以上版本。
使用 npm
安裝 gatsby-plugin-postcss
以及Tailwind 和它需要的依賴套件 (peer-dependencies):
npm install -D gatsby-plugin-postcss tailwindcss@latest postcss@latest autoprefixer@latest
然後產生 tailwind.config.js
和 postcss.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
檔案,並包含 tailwindcss
和 autoprefixer
的設定:
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
如果你打算使用別的 PostCSS 插件,你應該要閱讀我們在 using PostCSS as your preprocessor 的文件獲得更完整的資訊,來找出最合適的方式跟 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-config.js
檔案中啟用 postcss 插件。
// gatsby-config.js
module.exports = {
/* Your site config here */
- plugins: [],
+ plugins: ['gatsby-plugin-postcss'],
}
建立 ./src/styles/global.css
檔案
使用 @tailwind
指令來引用 Tailwind 的 base
、components
和 utilities
樣式,並且取代原本檔案的內容:
/* ./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 專案中運行。