Tailwind CSS v4 在2025年1月推出,主打在效能上有顯著的提升,配置也變得更簡便。依照指示一步一步來調整專案,可以簡單快速完成設定。
手動升級
1. 更新及安裝套件
安裝新版的 tailwindcss 和 @tailwindcss/postcss
npm install -D tailwindcss@4.1.12 @tailwindcss/postcss@4.1.12
兩個套件 autoprefixer和postcss 都可以從 package.json 中移除。
2. 調整 postcss.config.js
把新的套件設定放上去。
Beforeexport default { plugins: { "postcss-import": {}, // remove tailwindcss: {}, // remove autoprefixer: {}, // remove }, };After
export default { plugins: { "@tailwindcss/postcss": {}, // new }, };
3. 移除 @tailwind
Before@tailwind base; @tailwind components; @tailwind utilities;After
@import "tailwindcss";
我的專案本來就沒有使用 @tailwind,因為 SASS 的 @import 準備棄用(參考資料),因此使用 @use 也效果相同。
Before@use 'tailwindcss/base'; @use 'tailwindcss/components'; @use 'tailwindcss/utilities';After
@use "tailwindcss";
到這邊基本上就大功告成了,可以測試看看是不是都正常呢
自動升級
另外官方這次也有提供指令來進行升級:
npx @tailwindcss/upgrade
執行時目錄內不能有任何 unstaged files,否則不會進行任何操作。可以根據Terminal上的訊息了解到執行內容基本上相同。
因此除了專案配置以外的改變,需要再參考指南確認有哪些影響,如果有v3, v4之間不兼容的調整,需要手動修正這些地方。
同場加映,額外分享兩個這次的調整:
- Automatic content detection:過往會在tailwind.config.ts 內定義 content 偵測檔案範圍,v4不再依賴這個設定,可以大膽地把這些設定拿掉。當然!會自動忽略 .gitignore 內提及的範圍,來確保效能。
- First-party Vite plugin:Vite目前真的可以說是強勢的存在,v4也特地為它打造一個 plugin 取代 PostCSS,只要在 vite.config.ts 加入設定,就可以移除檔案 postcss.config.js 讓專案更乾淨。
沒有留言:
張貼留言