resources.PostProcess
{{ with resources.Get "css/main.css" }}
{{ if hugo.IsDevelopment }}
<link rel="stylesheet" href="{{ .RelPermalink }}">
{{ else }}
{{ with . | postCSS | minify | fingerprint | resources.PostProcess }}
<link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
{{ end }}
{{ end }}
{{ end }}
將資源標記為 resources.PostProcess
會將轉換步驟延遲到建置完成後執行。
當轉換鏈中的一個或多個步驟依賴於建置結果時,請呼叫 resources.PostProcess
。
一個典型的用例是使用 PostCSS 的 PurgeCSS 外掛移除未使用的 CSS 規則。
CSS 清理
- 步驟 1
- 安裝 Node.js。
- 步驟 2
- 在專案根目錄安裝所需的 Node.js 套件:
npm i -D postcss postcss-cli autoprefixer @fullhuman/postcss-purgecss
- 步驟 3
- 在專案根目錄創建 PostCSS 設定檔案。此檔案需命名為
postcss.config.js
或其他 支援的檔案名稱。例如:
const autoprefixer = require('autoprefixer');
const purgecss = require('@fullhuman/postcss-purgecss')({
content: ['./hugo_stats.json'],
defaultExtractor: content => {
const els = JSON.parse(content).htmlElements;
return [
...(els.tags || []),
...(els.classes || []),
...(els.ids || []),
];
},
safelist: [] // https://purgecss.com/safelisting.html
});
module.exports = {
plugins: [
autoprefixer,
process.env.HUGO_ENVIRONMENT !== 'development' ? purgecss : null
]
};
- 步驟 4
- 啟用建置網站時生成
hugo_stats.json
檔案的功能。如果僅用於生產環境建置,請考慮將其設置於 config/production 下。
hugo.
build:
buildStats:
enable: true
[build]
[build.buildStats]
enable = true
{
"build": {
"buildStats": {
"enable": true
}
}
}
參考 configure build 文檔以獲取更多詳細信息及選項。
- 步驟 5
- 將 CSS 檔案放置於
assets/css
目錄中。 - 步驟 6
- 如果當前環境不是
development
,則使用 PostCSS 處理資源:
{{ with resources.Get "css/main.css" }}
{{ if hugo.IsDevelopment }}
<link rel="stylesheet" href="{{ .RelPermalink }}">
{{ else }}
{{ with . | postCSS | minify | fingerprint | resources.PostProcess }}
<link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
{{ end }}
{{ end }}
{{ end }}
環境變數
Hugo 將這些環境變數傳遞給 PostCSS,因此您可以執行以下操作:
process.env.HUGO_ENVIRONMENT === 'production' ? [autoprefixer] : []
- PWD
- 專案工作目錄的絕對路徑。
- HUGO_ENVIRONMENT
- 當前 Hugo 環境,可通過
--environment
命令行參數設置。
默認為production
(hugo
指令)或development
(hugo server
指令)。 - HUGO_PUBLISHDIR
- 發佈目錄的絕對路徑(默認為
public
目錄)。注意,即使在hugo server
記憶體模式下,該值仍指向磁碟上的目錄。若您在server
模式下需要寫入該資料夾,請啟用以下選項之一:
hugo server --renderToDisk
hugo server --renderStaticToDisk
Hugo 也會為所有位於 assets/_jsconfig
目錄下的檔案設置環境變數。
let tailwindConfig = process.env.HUGO_FILE_TAILWIND_CONFIG_JS || './tailwind.config.js';
限制
- 不建議在 Hugo 的內建開發伺服器運行時使用
resources.PostProcess
。 - 僅適用於生成 HTML 檔案的模板。
- 無法操作從資源方法返回的值。例如,以下範例的
strings.ToUpper
函數將無法按預期工作:
{{ $css := resources.Get "css/main.css" }}
{{ $css = $css | css.PostCSS | minify | fingerprint | resources.PostProcess }}
{{ $css.RelPermalink | strings.ToUpper }}