hugo/docs/content/en/functions/resources/PostProcess.md

159 lines
5.4 KiB
Markdown
Raw Normal View History

---
title: resources.PostProcess
description: Processes the given resource after the build.
categories: []
keywords: []
action:
aliases: []
related:
Squashed 'docs/' changes from 9b06f951e..fcc3ed651 fcc3ed651 Remove some expired new-in a9c5981f5 Fix cascade example 82bb250fa Add some lines about permalinks tokens in front matter 328fe564e Remove some outdated new-in fb140b153 Hide showcase menu entry 42d9d1c79 Update image formats from which EXIF data can be extracted 09ad56b6e netlify: Hugo 0.130.0 1d503f846 Merge branch 'tempv0.130.0' e2458074d math: Add trigonometric functions and some angle helper functions 392afc8f9 Disable the showcase section for now 0300750f2 Improve example of image render hook 60a9306af Improve description of the .Site.RegularPages method 8d759175d Fix typos 55daa4554 Update XxHash.md 397c81cb7 Add namespace for hash functions 70fe8d2f0 netlify: Bump Hugo 0.129.0 5a9771aff Merge branch 'tempv0.129.0' f9146575b Fix typo e6e1fea49 Fix typo in Hugo docs | functions | partial 732d10ec4 source: Expose GitInfo Body 34c97e639 netlify: Hugo 0.128.2 3270587e9 Fix typo 727c5396e netlify: Hugo 0.128.1 80b6ae99c Update GitHub Pages workflow file example 027134102 Update GitHub Pages workflow file example 2600a8a2e Miscellaneous edits 3fdd5819b Update Build.md 7764005c3 Improve example of render hook directory structure 5e3941d82 Fix typos 748bf065f Restructure templates section fafbf6566 Update Defer.md 012162e0d Document changes to template functions in v0.128.0 0990ce35b quick-reference: Update emojis 6677a30ef Update Goldmark configuration documentation 4449d530d Document new pagination config 0af8be439 Update Defer.md 56348196d netlify: Hugo 0.128.0 d67b6d82e Update content/en/functions/templates/Defer.md 23d996b3d Update content/en/functions/templates/Defer.md 7f7fb2f27 Document templates.Defer 5ada1e9d5 Fix docs merge (remove shortcode) d27ee6156 Merge branch 'tempv0.128.0' 5d7317c84 Fix typo 7c18ee546 Update theme 83bfea63b Update theme b274b3238 Merge commit '8b9803425e63e1b1801f8d5d676e96368d706722' ff34a035a deploy: Add stripIndexHtml target option d9e964bdb markup/goldmark: Add the Hugo Goldmark Extras "delete" extension ac5bd16d2 deps: Upgrade github.com/alecthomas/chroma v2.13.0 => v2.14.0 25377171b config: Remove extraneous BuildConfig setting 0d2044f6d docs: Regen docshelper a2548dac9 markup/goldmark: Support extras extension 9d0c86ee8 commands: Add gen chromastyles --lineNumbersTableStyle flag git-subtree-dir: docs git-subtree-split: fcc3ed651a1b6431303c2f88f20fa38531c52b3d
2024-08-09 09:17:43 -04:00
- functions/css/PostCSS
- functions/css/Sass
returnType: postpub.PostPublishedResource
signatures: [resources.PostProcess RESOURCE]
toc: true
---
```go-html-template
{{ 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 }}
```
Marking a resource with `resources.PostProcess` postpones transformations until the build has finished.
Call `resources.PostProcess` when one or more of the steps in the transformation chain depends on the result of the build.
A prime use case for this is purging unused CSS rules using the [PurgeCSS] plugin for the PostCSS Node.js package.
## CSS Purging
{{% note %}}
There are several ways to set up CSS purging with PostCSS in Hugo. If you have a simple project, you should consider going the simpler route and drop the use of `resources.PostProcess` and just extract keywords from the templates. See the [Tailwind documentation](https://tailwindcss.com/docs/controlling-file-size/#app) for examples.
{{% /note %}}
Step 1
: Install [Node.js].
Step 2
: Install the required Node.js packages in the root of your project:
```sh
npm i -D postcss postcss-cli autoprefixer @fullhuman/postcss-purgecss
```
Step 3
: Create a PostCSS configuration file in the root of your project. You must name this file `postcss.config.js` or another [supported file name]. For example:
```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 || []),
];
},
// https://purgecss.com/safelisting.html
safelist: []
});
module.exports = {
plugins: [
autoprefixer,
process.env.HUGO_ENVIRONMENT !== 'development' ? purgecss : null
]
};
```
{{% note %}}
{{% include "functions/resources/_common/postcss-windows-warning.md" %}}
{{% /note %}}
Step 4
: Enable creation of the `hugo_stats.json` file when building the site. If you are only using this for the production build, consider placing it below [config/production].
{{< code-toggle file=hugo >}}
[build.buildStats]
enable = true
{{< /code-toggle >}}
See the [configure build] documentation for details and options.
Step 5
: Place your CSS file within the `assets/css` directory.
Step 6
: If the current environment is not `development`, process the resource with PostCSS:
```go-html-template
{{ 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 }}
```
## Environment variables
Hugo passes these environment variables to PostCSS, which allows you to do something like:
```js
process.env.HUGO_ENVIRONMENT === 'production' ? [autoprefixer] : []
```
PWD
: The absolute path to the project working directory.
HUGO_ENVIRONMENT
: The current Hugo environment, set with the `--environment` command line flag.
Default is `production` for `hugo` and `development` for `hugo server`.
HUGO_PUBLISHDIR
: The absolute path to the publish directory (the `public` directory). Note that the value will always point to a directory on disk even when running `hugo server` in memory mode. If you write to this folder from PostCSS when running the server, you could run the server with one of these flags:
```sh
hugo server --renderToDisk
hugo server --renderStaticToDisk
```
Also, Hugo will add environment variables for all files mounted below `assets/_jsconfig`. A default mount will be set up with files in the project root matching this regexp: `(babel|postcss|tailwind)\.config\.js`.
These will get environment variables named on the form `HUGO_FILE_:filename:` where `:filename:` is all upper case with periods replaced with underscore. This allows you to do something like:
```js
let tailwindConfig = process.env.HUGO_FILE_TAILWIND_CONFIG_JS || './tailwind.config.js';
```
## Limitations
Do not use `resources.PostProcess` when running Hugo's built-in development server. The examples above specifically prevent this by verifying that the current environment is not "development".
The `resources.PostProcess` function only works within templates that produce HTML files.
You cannot manipulate the values returned from the resources methods. For example, the `strings.ToUpper` function in this example will not work as expected:
```go-html-template
{{ $css := resources.Get "css/main.css" }}
Squashed 'docs/' changes from 9b06f951e..fcc3ed651 fcc3ed651 Remove some expired new-in a9c5981f5 Fix cascade example 82bb250fa Add some lines about permalinks tokens in front matter 328fe564e Remove some outdated new-in fb140b153 Hide showcase menu entry 42d9d1c79 Update image formats from which EXIF data can be extracted 09ad56b6e netlify: Hugo 0.130.0 1d503f846 Merge branch 'tempv0.130.0' e2458074d math: Add trigonometric functions and some angle helper functions 392afc8f9 Disable the showcase section for now 0300750f2 Improve example of image render hook 60a9306af Improve description of the .Site.RegularPages method 8d759175d Fix typos 55daa4554 Update XxHash.md 397c81cb7 Add namespace for hash functions 70fe8d2f0 netlify: Bump Hugo 0.129.0 5a9771aff Merge branch 'tempv0.129.0' f9146575b Fix typo e6e1fea49 Fix typo in Hugo docs | functions | partial 732d10ec4 source: Expose GitInfo Body 34c97e639 netlify: Hugo 0.128.2 3270587e9 Fix typo 727c5396e netlify: Hugo 0.128.1 80b6ae99c Update GitHub Pages workflow file example 027134102 Update GitHub Pages workflow file example 2600a8a2e Miscellaneous edits 3fdd5819b Update Build.md 7764005c3 Improve example of render hook directory structure 5e3941d82 Fix typos 748bf065f Restructure templates section fafbf6566 Update Defer.md 012162e0d Document changes to template functions in v0.128.0 0990ce35b quick-reference: Update emojis 6677a30ef Update Goldmark configuration documentation 4449d530d Document new pagination config 0af8be439 Update Defer.md 56348196d netlify: Hugo 0.128.0 d67b6d82e Update content/en/functions/templates/Defer.md 23d996b3d Update content/en/functions/templates/Defer.md 7f7fb2f27 Document templates.Defer 5ada1e9d5 Fix docs merge (remove shortcode) d27ee6156 Merge branch 'tempv0.128.0' 5d7317c84 Fix typo 7c18ee546 Update theme 83bfea63b Update theme b274b3238 Merge commit '8b9803425e63e1b1801f8d5d676e96368d706722' ff34a035a deploy: Add stripIndexHtml target option d9e964bdb markup/goldmark: Add the Hugo Goldmark Extras "delete" extension ac5bd16d2 deps: Upgrade github.com/alecthomas/chroma v2.13.0 => v2.14.0 25377171b config: Remove extraneous BuildConfig setting 0d2044f6d docs: Regen docshelper a2548dac9 markup/goldmark: Support extras extension 9d0c86ee8 commands: Add gen chromastyles --lineNumbersTableStyle flag git-subtree-dir: docs git-subtree-split: fcc3ed651a1b6431303c2f88f20fa38531c52b3d
2024-08-09 09:17:43 -04:00
{{ $css = $css | css.PostCSS | minify | fingerprint | resources.PostProcess }}
{{ $css.RelPermalink | strings.ToUpper }}
```
[node.js]: https://nodejs.org/en/download
[supported file name]: https://github.com/postcss/postcss-load-config#usage
[config/production]: /getting-started/configuration/#configuration-directory
[configure build]: /getting-started/configuration/#configure-build
[purgecss]: https://github.com/FullHuman/purgecss#readme