postprocess.md (2679B)
1 --- 2 title: PostProcess 3 description: Allows delaying of resource transformations to after the build. 4 date: 2020-04-09 5 categories: [asset management] 6 keywords: [] 7 menu: 8 docs: 9 parent: "pipes" 10 weight: 39 11 weight: 39 12 sections_weight: 39 13 --- 14 15 Marking a resource with `resources.PostProcess` delays any transformations to after the build, typically because one or more of the steps in the transformation chain depends on the result of the build (e.g. files in `public`).{{< new-in "0.69.0" >}} 16 17 A prime use case for this is [CSS purging with PostCSS](#css-purging-with-postcss). 18 19 There are currently two limitations to this: 20 21 1. This only works in `*.html` templates (i.e. templates that produces HTML files). 22 2. You cannot manipulate the values returned from the resource's methods. E.g. the `upper` in this example will not work as expected: 23 24 ```go-html-template 25 {{ $css := resources.Get "css/main.css" }} 26 {{ $css = $css | resources.PostCSS | minify | fingerprint | resources.PostProcess }} 27 {{ $css.RelPermalink | upper }} 28 ``` 29 30 ## CSS purging with PostCSS 31 32 {{% note %}} 33 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 some examples. 34 {{% /note %}} 35 36 The below configuration will write a `hugo_stats.json` file to the project root as part of the build. If you're only using this for the production build, you should consider placing it below [config/production](/getting-started/configuration/#configuration-directory). 37 38 {{< code-toggle file="config" >}} 39 [build] 40 writeStats = true 41 {{< /code-toggle >}} 42 43 `postcss.config.js` 44 45 ```js 46 const purgecss = require('@fullhuman/postcss-purgecss')({ 47 content: [ './hugo_stats.json' ], 48 defaultExtractor: (content) => { 49 let els = JSON.parse(content).htmlElements; 50 return els.tags.concat(els.classes, els.ids); 51 } 52 }); 53 54 module.exports = { 55 plugins: [ 56 ...(process.env.HUGO_ENVIRONMENT === 'production' ? [ purgecss ] : []) 57 ] 58 }; 59 ``` 60 61 Note that in the example above, the "CSS purge step" will only be applied to the production build. This means that you need to do something like this in your head template to build and include your CSS: 62 63 ```go-html-template 64 {{ $css := resources.Get "css/main.css" }} 65 {{ $css = $css | resources.PostCSS }} 66 {{ if hugo.IsProduction }} 67 {{ $css = $css | minify | fingerprint | resources.PostProcess }} 68 {{ end }} 69 <link href="{{ $css.RelPermalink }}" rel="stylesheet" /> 70 ```