css.PostCSS
New in v0.128.0
{{ with resources.Get "css/main.css" | postCSS }}
<link rel="stylesheet" href="{{ .RelPermalink }}">
{{ end }}
設定
按照以下步驟使用任何可用的 PostCSS 插件 來轉換 CSS。
- 步驟 1
- 安裝 Node.js。
- 步驟 2
- 在專案根目錄安裝所需的 Node.js 套件。例如,要為你的 CSS 規則添加廠商前綴:
npm i -D postcss postcss-cli autoprefixer
- 步驟 3
- 在專案根目錄建立 PostCSS 配置文件。該文件必須命名為
postcss.config.js
或其他 支援的檔案名稱。例如:
module.exports = {
plugins: [
require('autoprefixer')
]
};
- 步驟 4
- 將你的 CSS 檔案放在
assets/css
目錄中。 - 步驟 5
- 使用 PostCSS 處理資源:
{{ with resources.Get "css/main.css" | postCSS }}
<link rel="stylesheet" href="{{ .RelPermalink }}">
{{ end }}
選項
css.PostCSS
方法接受一個可選的選項映射。
- config
- (
string
) 包含 PostCSS 配置文件的目錄。預設為專案根目錄。 - noMap
- (
bool
) 預設為false
。若設為true
,將禁用內嵌的 source map。 - inlineImports
- (
bool
) 預設為false
。啟用內嵌@import
語句。它會遞迴處理,但只會匯入一次。URL 匯入(例如@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');
)和包含媒體查詢的匯入將會被忽略。請注意,此匯入過程不會檢查 CSS 規範,因此你可以在檔案中的任何位置使用@import
。Hugo 會根據模組掛載位置查找匯入並尊重主題覆蓋。 - skipInlineImportsNotFound
- (
bool
) 預設為false
。在 Hugo 0.99.0 之前,當啟用inlineImports
並無法解析匯入時,我們會記錄警告。現在會導致構建失敗。如果你有常規的 CSS 匯入並希望保留,你可以使用帶有 URL 或媒體查詢的匯入(Hugo 不會嘗試解析這些)或將skipInlineImportsNotFound
設為true
。
{{ $opts := dict "config" "config-directory" "noMap" true }}
{{ with resources.Get "css/main.css" | postCSS $opts }}
<link rel="stylesheet" href="{{ .RelPermalink }}">
{{ end }}
沒有配置文件
為了避免使用 PostCSS 配置文件,你可以使用選項映射來指定最小配置。
- use
- (
string
) 用空格分隔的 PostCSS 插件列表。 - parser
- (
string
) 自定義的 PostCSS 解析器。 - stringifier
- (
string
) 自定義的 PostCSS 字符串化器。 - syntax
- (
string
) 自定義的 PostCSS 語法。
{{ $opts := dict "use" "autoprefixer postcss-color-alpha" }}
{{ with resources.Get "css/main.css" | postCSS $opts }}
<link rel="stylesheet" href="{{ .RelPermalink }}">
{{ end }}
檢查環境
當前的 Hugo 環境名稱(由 --environment
或配置或作業系統環境設定)可用於 Node 上下文中,這允許像這樣的語法:
const autoprefixer = require('autoprefixer');
const purgecss = require('@fullhuman/postcss-purgecss');
module.exports = {
plugins: [
autoprefixer,
process.env.HUGO_ENVIRONMENT !== 'development' ? purgecss : null
]
}