PostCSS
預設行為 (Default Behavior)
Next.js 使用 PostCSS 為其內建 CSS 支援編譯 CSS。
Next.js 在無需任何設定的情況下,會使用以下轉換來編譯 CSS:
- Autoprefixer 會自動為 CSS 規則添加廠商前綴(支援至 IE11)。
- 跨瀏覽器的 Flexbox 錯誤 會被修正,使其行為符合 規範。
- 新的 CSS 功能會自動編譯以確保與 Internet Explorer 11 的相容性。
預設情況下,CSS Grid 和 自訂屬性(CSS 變數)不會為了支援 IE11 而進行編譯。
要為 IE11 編譯 CSS Grid 排版,您可以在 CSS 檔案的頂部放置以下註釋:
/* autoprefixer grid: autoplace */
您也可以透過以下(已收合)的 autoprefixer 設定,在整個專案中啟用對 CSS Grid Layout 的 IE11 支援。更多資訊請參考下方「自訂外掛程式」。
點擊以檢視啟用 CSS Grid Layout 的設定
{
"plugins": [
"postcss-flexbugs-fixes",
[
"postcss-preset-env",
{
"autoprefixer": {
"flexbox": "no-2009",
"grid": "autoplace"
},
"stage": 3,
"features": {
"custom-properties": false
}
}
]
]
}
CSS 變數不會被編譯,因為無法安全地執行此操作。如果您必須使用變數,請考慮使用類似 Sass 變數 的方法,這些變數會被 Sass 編譯掉。
自訂目標瀏覽器
Next.js 允許您透過 Browserslist 設定目標瀏覽器(適用於 Autoprefixer 和已編譯的 CSS 功能)。
要自訂 browserslist,請在您的 package.json
中建立一個 browserslist
鍵,如下所示:
{
"browserslist": [">0.3%", "not dead", "not op_mini all"]
}
您可以使用 browsersl.ist 工具來視覺化您所設定的目標瀏覽器。
CSS 模組
無需任何設定即可支援 CSS 模組。要為檔案啟用 CSS 模組,請將檔案重新命名為副檔名 .module.css
。
您可以在這裡了解更多關於 Next.js 的 CSS 模組支援。
自訂外掛程式
警告:當您定義自訂 PostCSS 設定檔時,Next.js 會完全停用預設行為。請務必手動設定您需要編譯的所有功能,包括Autoprefixer。您還需要手動安裝自訂設定中包含的所有外掛程式,例如:
npm install postcss-flexbugs-fixes postcss-preset-env
。
要自訂 PostCSS 設定,請在專案的根目錄中建立一個 postcss.config.json
檔案。
這是 Next.js 使用的預設設定。
{
"plugins": [
"postcss-flexbugs-fixes",
[
"postcss-preset-env",
{
"autoprefixer": {
"flexbox": "no-2009"
},
"stage": 3,
"features": {
"custom-properties": false
}
}
]
]
}
注意事項:Next.js 也允許將檔案命名為
.postcssrc.json
,或者從package.json
中的postcss
鍵讀取。
也可以使用 postcss.config.js
檔案來設定 PostCSS,這在您想要根據環境條件式包含外掛程式時非常有用。
module.exports = {
plugins:
process.env.NODE_ENV === 'production'
? [
'postcss-flexbugs-fixes',
[
'postcss-preset-env',
{
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
features: {
'custom-properties': false,
},
},
],
]
: [
// No transformations in development
],
}
注意事項:Next.js 也允許將檔案命名為
.postcssrc.js
。
不要使用 require()
來匯入 PostCSS 外掛程式。外掛程式必須以字串形式提供。
注意事項:如果您的
postcss.config.js
需要在同一個專案中支援其他非 Next.js 工具,則必須使用可互操作的基於物件的格式。module.exports = { plugins: { 'postcss-flexbugs-fixes': {}, 'postcss-preset-env': { autoprefixer: { flexbox: 'no-2009', }, stage: 3, features: { 'custom-properties': false, }, }, }, }
這有幫助嗎?