css.PostCSS
- Syntax
- css.PostCSS [OPTIONS] RESOURCE
- Returns
- resource.Resource
- Alias
- postCSS
Usage
The css.PostCSS function returns a resource created by processing the given CSS resource with PostCSS and any of its plugins.
By default, Hugo searches the root of the project directory and of each module for postcss.config.js, postcss.config.mjs, and postcss.config.cjs, in that order. To use a configuration file in a different location, set the config option.
Hugo caches the result in memory and writes it to disk in the assets file cache, which is the resources/_gen directory by default. With the default useResourceCacheWhen setting, Hugo runs PostCSS on every build, and reads the result from the file cache only if it cannot find the PostCSS executable.
If you commit the resources directory to your repository, you do not need to install PostCSS on your CI/CD platform, because Hugo reads the result from the file cache. This works only if both of these conditions are true:
- You have not changed the location of the
assetsfile cache. - You have not set
useResourceCacheWhentoneverin your project configuration.
Requirements
To use this function, install Node.js, then install PostCSS and its command-line interface in the root of your project:
npm install --save-dev postcss postcss-cliInstall any PostCSS plugins that you use the same way.
Environment variables
Hugo passes these environment variables to the PostCSS process, so you can use them in your PostCSS configuration file:
PWD- The absolute path to the project working directory.
HUGO_ENVIRONMENT- The current Hugo environment, set with the
--environmentcommand-line flag or theHUGO_ENVIRONMENTenvironment variable. If you set both, the flag takes precedence. Default isproductionforhugo buildanddevelopmentforhugo server. HUGO_PUBLISHDIR- The absolute path to the
publicdirectory. This value points to a directory on disk, even when you render to memory with the--renderToMemorycommand-line flag. NODE_PATH- The absolute path to the
node_modulesdirectory in the root of your project. If theNODE_PATHenvironment variable is already set, Hugo appends its value. HUGO_FILE_<NAME>- The absolute path to a configuration file in the root of your project, where
<NAME>is the file name in uppercase with each period replaced by an underscore. For example,HUGO_FILE_TAILWIND_CONFIG_JSis the path to thetailwind.config.jsfile. Hugo creates a variable for each of these files that exists:babel.config.js,babel.config.mjs, andbabel.config.cjspackage.jsonpostcss.config.js,postcss.config.mjs, andpostcss.config.cjstailwind.config.js,tailwind.config.mjs, andtailwind.config.cjs
Use these variables to access the files from your JavaScript code:
let tailwindConfig = process.env.HUGO_FILE_TAILWIND_CONFIG_JS || './tailwind.config.js';
File system access
Hugo runs the Node.js tool used by this function with a permission model that limits the files the tool can read to the paths in security.node.permissions.allowRead. By default, this is the project directory. If the tool needs to read files from other locations, such as configuration files, plugins, or imported files in the node_modules directory of a parent directory in a monorepo, add those paths to the list.
Options
The css.PostCSS function accepts an options map. This option applies when you use a PostCSS configuration file:
config- (
string) The path to the directory that contains the PostCSS configuration file. Hugo resolves a relative path against the root of the project directory and of each module. The directory must contain a file namedpostcss.config.js,postcss.config.mjs, orpostcss.config.cjs. Otherwise, the build fails. If you pass the path to a file, PostCSS ignores the file name and uses the directory that contains the file. Use this option only if your configuration file is in a custom subdirectory.
Hugo handles these options itself, so they apply with or without a PostCSS configuration file:
importContext- New in v0.165.0
- (
resource.ResourceGetter) A resource getter to use when resolving@importstatements. Hugo searches this context first, before falling back to the file system. Hugo matches a resource in the context by the path relative to theassetsdirectory. For a path that begins with./or../, Hugo resolves the path relative to the importing file. For example, when theassets/css/main.cssfile contains@import "./sub/theme.css", a resource namedcss/sub/theme.cssmatches. For a bare path, Hugo also tries the path as written, so@import "sub/theme.css"matches a resource namedsub/theme.cssorcss/sub/theme.css. Applicable wheninlineImportsistrue. inlineImports- (
bool) Whether to replace@importstatements with the content of the imported files. Hugo replaces the statements recursively, but imports each file only once. Hugo resolves each import relative to the importing file, within theassetsdirectory of the unified file system, even if the path begins with a slash. Default isfalse.The import routine does not follow the CSS specification, so you can place
@importstatements anywhere in the file. Hugo does not replace imports with media queries or imports that use theurl()functional notation, such as:@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');Hugo treats an import of an external URL without the
url()functional notation, such as@import "https://example.org/styles.css", as an import of a local file. The build fails unless you set theskipInlineImportsNotFoundoption totrue. skipInlineImportsNotFound- (
bool) Whether to continue the build when Hugo cannot resolve an@importstatement, preserving the original statement. Set this option totrueto keep standard CSS imports that Hugo cannot resolve. Default isfalse.
These options apply when you configure PostCSS without a configuration file:
noMap- (
bool) Whether to disable the default inline source maps. Default isfalse. parser- (
string) A custom PostCSS parser. stringifier- (
string) A custom PostCSS stringifier. syntax- (
string) A custom PostCSS syntax. use- (
string) A space-delimited list of PostCSS plugins to use.
Examples
These examples configure PostCSS with a configuration file and with the options map.
Configuration file
This example uses a PostCSS configuration file to add vendor prefixes in production, and to generate an inline source map in development.
- Step 1
- Install the
autoprefixerplugin, which adds vendor prefixes to your CSS:npm install --save-dev autoprefixer - Step 2
- Create a PostCSS configuration file in the root of your project. The configuration uses the
HUGO_ENVIRONMENTenvironment variable to apply different settings in development and production:postcss.config.mjsimport autoprefixer from 'autoprefixer'; const isDev = process.env.HUGO_ENVIRONMENT === 'development'; export default { plugins: [ !isDev ? autoprefixer : null ], map: isDev ? { inline: true } : false }; - Step 3
- Create a partial template to process the
assets/css/main.cssfile:layouts/_partials/css.html{{ with resources.Get "css/main.css" }} {{ $opts := dict "inlineImports" true }} {{ with . | css.PostCSS $opts }} {{ if hugo.IsDevelopment }} <link rel="stylesheet" href="{{ .RelPermalink }}"> {{ else }} {{ with . | minify | fingerprint }} <link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous"> {{ end }} {{ end }} {{ end }} {{ end }} - Step 4
- Call the partial template from your base template:layouts/baseof.html
<head> {{ partial "css.html" . }} </head>
When you run the hugo server command, PostCSS skips the vendor prefixes and adds an inline source map. When you run the hugo build command, PostCSS adds the vendor prefixes and omits the source map.
Options map
This example sets the plugins and disables the source map with the options map instead of a configuration file. The postcss-nesting plugin converts nested CSS rules to flat rules for older browsers, and the autoprefixer plugin adds vendor prefixes. Install the plugins before you use them:
npm install --save-dev postcss-nesting autoprefixerThen pass the plugins to the css.PostCSS function, in the order that PostCSS runs them:
{{ with resources.Get "css/main.css" }}
{{ $opts := dict
"noMap" true
"use" "postcss-nesting autoprefixer"
}}
{{ with . | css.PostCSS $opts }}
{{ if hugo.IsDevelopment }}
<link rel="stylesheet" href="{{ .RelPermalink }}">
{{ else }}
{{ with . | fingerprint }}
<link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
{{ end }}
{{ end }}
{{ end }}
{{ end }}