mirror of
https://github.com/gohugoio/hugo.git
synced 2025-08-28 22:19:59 +02:00
Merge commit '9b0050e9aabe4be65c78ccf292a348f309d50ccd' as 'docs'
``` git subtree add --prefix=docs/ https://github.com/gohugoio/hugoDocs.git master --squash ``` Closes #11925
This commit is contained in:
12
docs/content/en/hugo-pipes/_index.md
Executable file
12
docs/content/en/hugo-pipes/_index.md
Executable file
@@ -0,0 +1,12 @@
|
||||
---
|
||||
title: Hugo Pipes
|
||||
linkTitle: Overview
|
||||
categories: []
|
||||
keywords: []
|
||||
menu:
|
||||
docs:
|
||||
identifier: hugo-pipes-overview
|
||||
parent: hugo-pipes
|
||||
weight: 10
|
||||
weight: 10
|
||||
---
|
76
docs/content/en/hugo-pipes/babel.md
Executable file
76
docs/content/en/hugo-pipes/babel.md
Executable file
@@ -0,0 +1,76 @@
|
||||
---
|
||||
title: Babel
|
||||
description: Hugo Pipes can process JS files with Babel.
|
||||
categories: [asset management]
|
||||
keywords: []
|
||||
menu:
|
||||
docs:
|
||||
parent: hugo-pipes
|
||||
weight: 70
|
||||
weight: 70
|
||||
function:
|
||||
aliases: [babel]
|
||||
returnType: resource.Resource
|
||||
signatures: ['resources.Babel [OPTIONS] RESOURCE']
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
Any JavaScript resource file can be transpiled to another JavaScript version using `resources.Babel` which takes for argument the resource object and an optional dict of options listed below. Babel uses the [babel cli](https://babeljs.io/docs/en/babel-cli).
|
||||
|
||||
{{% note %}}
|
||||
Hugo Pipe's Babel requires the `@babel/cli` and `@babel/core` JavaScript packages to be installed in the project or globally (`npm install -g @babel/cli @babel/core`) along with any Babel plugin(s) or preset(s) used (e.g., `npm install @babel/preset-env --save-dev`).
|
||||
|
||||
If you are using the Hugo Snap package, Babel and plugin(s) need to be installed locally within your Hugo site directory, e.g., `npm install @babel/cli @babel/core --save-dev` without the `-g` flag.
|
||||
{{% /note %}}
|
||||
|
||||
## Configuration
|
||||
|
||||
We add the main project's `node_modules` to `NODE_PATH` when running Babel and similar tools. There are some known [issues](https://github.com/babel/babel/issues/5618) with Babel in this area, so if you have a `babel.config.js` living in a Hugo Module (and not in the project itself), we recommend using `require` to load the presets/plugins, e.g.:
|
||||
|
||||
```js
|
||||
module.exports = {
|
||||
presets: [
|
||||
[
|
||||
require("@babel/preset-env"),
|
||||
{
|
||||
useBuiltIns: "entry",
|
||||
corejs: 3,
|
||||
},
|
||||
],
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
config
|
||||
: (`string`) Path to the Babel configuration file. Hugo will, by default, look for a `babel.config.js` in your project. More information on these configuration files can be found here: [babel configuration](https://babeljs.io/docs/en/configuration).
|
||||
|
||||
minified
|
||||
: (`bool`) Save as many bytes as possible when printing
|
||||
|
||||
noComments
|
||||
: (`bool`) Write comments to generated output (true by default)
|
||||
|
||||
compact
|
||||
: (`bool`) Do not include superfluous whitespace characters and line terminators. Defaults to `auto` if not set.
|
||||
|
||||
verbose
|
||||
: (`bool`) Log everything
|
||||
|
||||
sourceMap
|
||||
: (`string`) Output `inline` or `external` sourcemap from the babel compile. External sourcemaps will be written to the target with the output file name + ".map". Input sourcemaps can be read from js.Build and node modules and combined into the output sourcemaps.
|
||||
|
||||
## Examples
|
||||
|
||||
```go-html-template
|
||||
{{- $transpiled := resources.Get "scripts/main.js" | babel -}}
|
||||
```
|
||||
|
||||
Or with options:
|
||||
|
||||
```go-html-template
|
||||
{{ $opts := dict "noComments" true }}
|
||||
{{- $transpiled := resources.Get "scripts/main.js" | babel $opts -}}
|
||||
```
|
26
docs/content/en/hugo-pipes/bundling.md
Executable file
26
docs/content/en/hugo-pipes/bundling.md
Executable file
@@ -0,0 +1,26 @@
|
||||
---
|
||||
title: Concat
|
||||
linkTitle: Concatenating assets
|
||||
description: Bundle any number of assets into one resource.
|
||||
categories: [asset management]
|
||||
keywords: []
|
||||
menu:
|
||||
docs:
|
||||
parent: hugo-pipes
|
||||
weight: 90
|
||||
weight: 90
|
||||
action:
|
||||
aliases: []
|
||||
returnType: resource.Resource
|
||||
signatures: ['resources.Concat TARGETPATH [RESOURCE...]']
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
Asset files of the same MIME type can be bundled into one resource using `resources.Concat` which takes two arguments, the target path for the created resource bundle and a slice of resource objects to be concatenated.
|
||||
|
||||
```go-html-template
|
||||
{{ $plugins := resources.Get "js/plugins.js" }}
|
||||
{{ $global := resources.Get "js/global.js" }}
|
||||
{{ $js := slice $plugins $global | resources.Concat "js/bundle.js" }}
|
||||
```
|
30
docs/content/en/hugo-pipes/fingerprint.md
Executable file
30
docs/content/en/hugo-pipes/fingerprint.md
Executable file
@@ -0,0 +1,30 @@
|
||||
---
|
||||
title: Fingerprint
|
||||
linkTitle: Fingerprinting and SRI hashing
|
||||
description: Process a given resource, adding a hash string of the resource's content.
|
||||
categories: [asset management]
|
||||
keywords: []
|
||||
menu:
|
||||
docs:
|
||||
parent: hugo-pipes
|
||||
weight: 100
|
||||
weight: 100
|
||||
action:
|
||||
aliases: [fingerprint]
|
||||
returnType: resource.Resource
|
||||
signatures: ['resources.Fingerprint [ALGORITHM] RESOURCE']
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
Fingerprinting and [SRI](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) can be applied to any asset file using `resources.Fingerprint` which takes two arguments, the resource object and an optional [hash algorithm](https://en.wikipedia.org/wiki/Secure_Hash_Algorithms).
|
||||
|
||||
The default hash algorithm is `sha256`. Other available algorithms are `sha384` and (as of Hugo `0.55`) `sha512` and `md5`.
|
||||
|
||||
Any so processed asset will bear a `.Data.Integrity` property containing an integrity string, which is made up of the name of the hash algorithm, one hyphen and the base64-encoded hash sum.
|
||||
|
||||
```go-html-template
|
||||
{{ $js := resources.Get "js/global.js" }}
|
||||
{{ $secureJS := $js | resources.Fingerprint "sha512" }}
|
||||
<script src="{{ $secureJS.Permalink }}" integrity="{{ $secureJS.Data.Integrity }}"></script>
|
||||
```
|
79
docs/content/en/hugo-pipes/introduction.md
Executable file
79
docs/content/en/hugo-pipes/introduction.md
Executable file
@@ -0,0 +1,79 @@
|
||||
---
|
||||
title: Hugo Pipes
|
||||
linkTitle: Introduction
|
||||
description: Hugo Pipes is Hugo's asset processing set of functions.
|
||||
categories: [asset management]
|
||||
keywords: []
|
||||
menu:
|
||||
docs:
|
||||
parent: hugo-pipes
|
||||
weight: 20
|
||||
weight: 20
|
||||
toc: true
|
||||
aliases: [/assets/]
|
||||
---
|
||||
|
||||
## Find resources in assets
|
||||
|
||||
This is about global and remote resources.
|
||||
|
||||
global resource
|
||||
: A file within the assets directory, or within any directory [mounted] to the assets directory.
|
||||
|
||||
remote resource
|
||||
: A file on a remote server, accessible via HTTP or HTTPS.
|
||||
|
||||
For `.Page` scoped resources, see the [page resources] section.
|
||||
|
||||
[mounted]: /hugo-modules/configuration/#module-configuration-mounts
|
||||
[page resources]: /content-management/page-resources/
|
||||
|
||||
## Get a resource
|
||||
|
||||
In order to process an asset with Hugo Pipes, it must be retrieved as a resource.
|
||||
|
||||
For global resources, use:
|
||||
|
||||
- [`resources.ByType`](/functions/resources/bytype/)
|
||||
- [`resources.Get`](/functions/resources/get/)
|
||||
- [`resources.GetMatch`](/functions/resources/getmatch/)
|
||||
- [`resources.Match`](/functions/resources/match/)
|
||||
|
||||
For remote resources, use:
|
||||
|
||||
- [`resources.GetRemote`](/functions/resources/getremote/)
|
||||
|
||||
See the [GoDoc Page](https://pkg.go.dev/github.com/gohugoio/hugo/tpl/resources) for the `resources` package for an up to date overview of all template functions in this namespace.
|
||||
|
||||
## Copy a resource
|
||||
|
||||
See the [`resources.Copy`](/functions/resources/copy/) function.
|
||||
|
||||
## Asset directory
|
||||
|
||||
Asset files must be stored in the asset directory. This is `/assets` by default, but can be configured via the configuration file's `assetDir` key.
|
||||
|
||||
## Asset publishing
|
||||
|
||||
Hugo publishes assets to the `publishDir` (typically `public`) when you invoke `.Permalink`, `.RelPermalink`, or `.Publish`. You can use `.Content` to inline the asset.
|
||||
|
||||
## Go Pipes
|
||||
|
||||
For improved readability, the Hugo Pipes examples of this documentation will be written using [Go Pipes](/templates/introduction/#pipes):
|
||||
|
||||
```go-html-template
|
||||
{{ $style := resources.Get "sass/main.scss" | resources.ToCSS | resources.Minify | resources.Fingerprint }}
|
||||
<link rel="stylesheet" href="{{ $style.Permalink }}">
|
||||
```
|
||||
|
||||
## Caching
|
||||
|
||||
Hugo Pipes invocations are cached based on the entire *pipe chain*.
|
||||
|
||||
An example of a pipe chain is:
|
||||
|
||||
```go-html-template
|
||||
{{ $mainJs := resources.Get "js/main.js" | js.Build "main.js" | minify | fingerprint }}
|
||||
```
|
||||
|
||||
The pipe chain is only invoked the first time it is encountered in a site build, and results are otherwise loaded from cache. As such, Hugo Pipes can be used in templates which are executed thousands or millions of times without negatively impacting the build performance.
|
166
docs/content/en/hugo-pipes/js.md
Normal file
166
docs/content/en/hugo-pipes/js.md
Normal file
@@ -0,0 +1,166 @@
|
||||
---
|
||||
title: js.Build
|
||||
linkTitle: JavaScript building
|
||||
description: Bundle, transpile, tree shake, and minify JavaScript resources.
|
||||
categories: [asset management]
|
||||
keywords: []
|
||||
menu:
|
||||
docs:
|
||||
parent: hugo-pipes
|
||||
weight: 60
|
||||
weight: 60
|
||||
action:
|
||||
aliases: []
|
||||
returnType: resource.Resource
|
||||
signatures: ['js.Build [OPTIONS] RESOURCE']
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
Any JavaScript resource file can be transpiled and "tree shaken" using `js.Build` which takes for argument either a string for the filepath or a dict of options listed below.
|
||||
|
||||
### Options
|
||||
|
||||
targetPath
|
||||
: (`string`) If not set, the source path will be used as the base target path.
|
||||
Note that the target path's extension may change if the target MIME type is different, e.g. when the source is TypeScript.
|
||||
|
||||
params {{< new-in "0.96.0" >}}
|
||||
: (`map` or `slice`) Params that can be imported as JSON in your JS files, e.g.:
|
||||
|
||||
```go-html-template
|
||||
{{ $js := resources.Get "js/main.js" | js.Build (dict "params" (dict "api" "https://example.org/api")) }}
|
||||
```
|
||||
And then in your JS file:
|
||||
|
||||
```js
|
||||
import * as params from '@params';
|
||||
```
|
||||
|
||||
Note that this is meant for small data sets, e.g. configuration settings. For larger data, please put/mount the files into `/assets` and import them directly.
|
||||
|
||||
minify
|
||||
: (`bool`) Let `js.Build` handle the minification.
|
||||
|
||||
inject
|
||||
: (`slice`) This option allows you to automatically replace a global variable with an import from another file. The path names must be relative to `assets`. See https://esbuild.github.io/api/#inject
|
||||
|
||||
shims
|
||||
: (`map`) This option allows swapping out a component with another. A common use case is to load dependencies like React from a CDN (with _shims_) when in production, but running with the full bundled `node_modules` dependency during development:
|
||||
|
||||
```go-html-template
|
||||
{{ $shims := dict "react" "js/shims/react.js" "react-dom" "js/shims/react-dom.js" }}
|
||||
{{ $js = $js | js.Build dict "shims" $shims }}
|
||||
```
|
||||
|
||||
The _shim_ files may look like these:
|
||||
|
||||
```js
|
||||
// js/shims/react.js
|
||||
module.exports = window.React;
|
||||
```
|
||||
|
||||
```js
|
||||
// js/shims/react-dom.js
|
||||
module.exports = window.ReactDOM;
|
||||
```
|
||||
|
||||
With the above, these imports should work in both scenarios:
|
||||
|
||||
```js
|
||||
import * as React from 'react'
|
||||
import * as ReactDOM from 'react-dom';
|
||||
```
|
||||
|
||||
target
|
||||
: (`string`) The language target.
|
||||
One of: `es5`, `es2015`, `es2016`, `es2017`, `es2018`, `es2019`, `es2020` or `esnext`.
|
||||
Default is `esnext`.
|
||||
|
||||
externals
|
||||
: (`slice`) External dependencies. Use this to trim dependencies you know will never be executed. See https://esbuild.github.io/api/#external
|
||||
|
||||
defines
|
||||
: (`map`) Allow to define a set of string replacement to be performed when building. Should be a map where each key is to be replaced by its value.
|
||||
|
||||
```go-html-template
|
||||
{{ $defines := dict "process.env.NODE_ENV" `"development"` }}
|
||||
```
|
||||
|
||||
format
|
||||
: (`string`) The output format.
|
||||
One of: `iife`, `cjs`, `esm`.
|
||||
Default is `iife`, a self-executing function, suitable for inclusion as a `<script>` tag.
|
||||
|
||||
sourceMap
|
||||
: (`string`) Whether to generate `inline` or `external` source maps from esbuild. External source maps will be written to the target with the output file name + ".map". Input source maps can be read from js.Build and node modules and combined into the output source maps. By default, source maps are not created.
|
||||
|
||||
### Import JS code from /assets
|
||||
|
||||
`js.Build` has full support for the virtual union file system in [Hugo Modules](/hugo-modules/). You can see some simple examples in this [test project](https://github.com/gohugoio/hugoTestProjectJSModImports), but in short this means that you can do this:
|
||||
|
||||
```js
|
||||
import { hello } from 'my/module';
|
||||
```
|
||||
|
||||
And it will resolve to the top-most `index.{js,ts,tsx,jsx}` inside `assets/my/module` in the layered file system.
|
||||
|
||||
```js
|
||||
import { hello3 } from 'my/module/hello3';
|
||||
```
|
||||
|
||||
Will resolve to `hello3.{js,ts,tsx,jsx}` inside `assets/my/module`.
|
||||
|
||||
Any imports starting with `.` is resolved relative to the current file:
|
||||
|
||||
```js
|
||||
import { hello4 } from './lib';
|
||||
```
|
||||
|
||||
For other files (e.g. `JSON`, `CSS`) you need to use the relative path including any extension, e.g:
|
||||
|
||||
```js
|
||||
import * as data from 'my/module/data.json';
|
||||
```
|
||||
|
||||
Any imports in a file outside `/assets` or that does not resolve to a component inside `/assets` will be resolved by [ESBuild](https://esbuild.github.io/) with the **project directory** as the resolve directory (used as the starting point when looking for `node_modules` etc.). Also see [hugo mod npm pack](/commands/hugo_mod_npm_pack/). If you have any imported npm dependencies in your project, you need to make sure to run `npm install` before you run `hugo`.
|
||||
|
||||
Also note the new `params` option that can be passed from template to your JS files, e.g.:
|
||||
|
||||
```go-html-template
|
||||
{{ $js := resources.Get "js/main.js" | js.Build (dict "params" (dict "api" "https://example.org/api")) }}
|
||||
```
|
||||
And then in your JS file:
|
||||
|
||||
```js
|
||||
import * as params from '@params';
|
||||
```
|
||||
|
||||
Hugo will, by default, generate a `assets/jsconfig.json` file that maps the imports. This is useful for navigation/intellisense help inside code editors, but if you don't need/want it, you can [turn it off](/getting-started/configuration/#configure-build).
|
||||
|
||||
### Include dependencies In package.json / node_modules
|
||||
|
||||
Any imports in a file outside `/assets` or that does not resolve to a component inside `/assets` will be resolved by [ESBuild](https://esbuild.github.io/) with the **project directory** as the resolve directory (used as the starting point when looking for `node_modules` etc.). Also see [hugo mod npm pack](/commands/hugo_mod_npm_pack/). If you have any imported npm dependencies in your project, you need to make sure to run `npm install` before you run `hugo`.
|
||||
|
||||
The start directory for resolving npm packages (aka. packages that live inside a `node_modules` folder) is always the main project folder.
|
||||
|
||||
{{% note %}}
|
||||
If you're developing a theme/component that is supposed to be imported and depends on dependencies inside `package.json`, we recommend reading about [hugo mod npm pack](/commands/hugo_mod_npm_pack/), a tool to consolidate all the npm dependencies in a project.
|
||||
{{% /note %}}
|
||||
|
||||
### Examples
|
||||
|
||||
```go-html-template
|
||||
{{ $built := resources.Get "js/index.js" | js.Build "main.js" }}
|
||||
```
|
||||
|
||||
Or with options:
|
||||
|
||||
```go-html-template
|
||||
{{ $externals := slice "react" "react-dom" }}
|
||||
{{ $defines := dict "process.env.NODE_ENV" `"development"` }}
|
||||
|
||||
{{ $opts := dict "targetPath" "main.js" "externals" $externals "defines" $defines }}
|
||||
{{ $built := resources.Get "scripts/main.js" | js.Build $opts }}
|
||||
<script src="{{ $built.RelPermalink }}" defer></script>
|
||||
```
|
27
docs/content/en/hugo-pipes/minification.md
Executable file
27
docs/content/en/hugo-pipes/minification.md
Executable file
@@ -0,0 +1,27 @@
|
||||
---
|
||||
title: Minify
|
||||
linkTitle: Asset minification
|
||||
description: Minifies a given resource.
|
||||
categories: [asset management]
|
||||
keywords: []
|
||||
menu:
|
||||
docs:
|
||||
parent: hugo-pipes
|
||||
weight: 80
|
||||
weight: 80
|
||||
action:
|
||||
aliases: [minify]
|
||||
returnType: resource.Resource
|
||||
signatures: [resources.Minify RESOURCE]
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
Any CSS, JS, JSON, HTML, SVG, or XML resource can be minified using `resources.Minify` which takes for argument the resource object.
|
||||
|
||||
```go-html-template
|
||||
{{ $css := resources.Get "css/main.css" }}
|
||||
{{ $style := $css | resources.Minify }}
|
||||
```
|
||||
|
||||
Note that you can also minify the final HTML output to `/public` by running `hugo --minify`.
|
131
docs/content/en/hugo-pipes/postcss.md
Executable file
131
docs/content/en/hugo-pipes/postcss.md
Executable file
@@ -0,0 +1,131 @@
|
||||
---
|
||||
title: PostCSS
|
||||
description: Process CSS files with PostCSS, using any of the available plugins.
|
||||
categories: [asset management]
|
||||
keywords: []
|
||||
menu:
|
||||
docs:
|
||||
parent: hugo-pipes
|
||||
weight: 40
|
||||
weight: 40
|
||||
toc: true
|
||||
action:
|
||||
aliases: [postCSS]
|
||||
returnType: resource.Resource
|
||||
signatures: ['resources.PostCSS [OPTIONS] RESOURCE']
|
||||
---
|
||||
|
||||
## Setup
|
||||
|
||||
Follow the steps below to transform CSS using any of the [available PostCSS plugins](https://www.postcss.parts/).
|
||||
|
||||
Step 1
|
||||
: Install [Node.js](https://nodejs.org/en/download).
|
||||
|
||||
Step 2
|
||||
: Install the required Node.js packages in the root of your project. For example, to add vendor prefixes to CSS rules:
|
||||
|
||||
```sh
|
||||
npm i -D postcss postcss-cli autoprefixer
|
||||
```
|
||||
|
||||
Step 3
|
||||
: Create a PostCSS configuration file in the root of your project. You must name this file `postcss.config.js` or one of the other [supported file names]. For example:
|
||||
|
||||
[supported file names]: https://github.com/postcss/postcss-load-config#usage
|
||||
|
||||
{{< code file=postcss.config.js >}}
|
||||
module.exports = {
|
||||
plugins: [
|
||||
require('autoprefixer')
|
||||
]
|
||||
};
|
||||
{{< /code >}}
|
||||
|
||||
{{% note %}}
|
||||
If you are a Windows user, and the path to your project contains a space, you must place the PostCSS configuration within the package.json file. See [this example](https://github.com/postcss/postcss-load-config#packagejson) and issue [#7333](https://github.com/gohugoio/hugo/issues/7333).
|
||||
{{% /note %}}
|
||||
|
||||
Step 4
|
||||
: Place your CSS file within the `assets` directory.
|
||||
|
||||
Step 5
|
||||
: Capture the CSS file as a resource and pipe it through `resources.PostCSS` (alias `postCSS`):
|
||||
|
||||
{{< code file=layouts/partials/css.html >}}
|
||||
{{ with resources.Get "css/main.css" | postCSS }}
|
||||
<link rel="stylesheet" href="{{ .RelPermalink }}">
|
||||
{{ end }}
|
||||
{{< /code >}}
|
||||
|
||||
If starting with a Sass file within the `assets` directory:
|
||||
|
||||
{{< code file=layouts/partials/css.html >}}
|
||||
{{ with resources.Get "sass/main.scss" | toCSS | postCSS }}
|
||||
<link rel="stylesheet" href="{{ .RelPermalink }}">
|
||||
{{ end }}
|
||||
{{< /code >}}
|
||||
|
||||
## Options
|
||||
|
||||
The `resources.PostCSS` method takes an optional map of options.
|
||||
|
||||
config
|
||||
: (`string`) The directory that contains the PostCSS configuration file. Default is the root of the project directory.
|
||||
|
||||
noMap
|
||||
: (`bool`) Default is `false`. If `true`, disables inline sourcemaps.
|
||||
|
||||
inlineImports
|
||||
: (`bool`) Default is `false`. Enable inlining of @import statements. It does so recursively, but will only import a file once.
|
||||
URL imports (e.g. `@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');`) and imports with media queries will be ignored.
|
||||
Note that this import routine does not care about the CSS spec, so you can have @import anywhere in the file.
|
||||
Hugo will look for imports relative to the module mount and will respect theme overrides.
|
||||
|
||||
skipInlineImportsNotFound {{< new-in 0.99.0 >}}
|
||||
: (`bool`) Default is `false`. Before Hugo 0.99.0 when `inlineImports` was enabled and we failed to resolve an import, we logged it as a warning. We now fail the build. If you have regular CSS imports in your CSS that you want to preserve, you can either use imports with URL or media queries (Hugo does not try to resolve those) or set `skipInlineImportsNotFound` to true.
|
||||
|
||||
{{< code file=layouts/partials/css.html >}}
|
||||
{{ $opts := dict "config" "config-directory" "noMap" true }}
|
||||
{{ with resources.Get "css/main.css" | postCSS $opts }}
|
||||
<link rel="stylesheet" href="{{ .RelPermalink }}">
|
||||
{{ end }}
|
||||
{{< /code >}}
|
||||
|
||||
## No configuration file
|
||||
|
||||
To avoid using a PostCSS configuration file, you can specify a minimal configuration using the options map.
|
||||
|
||||
use
|
||||
: (`string`) A space-delimited list of PostCSS plugins to use.
|
||||
|
||||
parser
|
||||
: (`string`) A custom PostCSS parser.
|
||||
|
||||
stringifier
|
||||
: (`string`) A custom PostCSS stringifier.
|
||||
|
||||
syntax
|
||||
: (`string`) Custom postcss syntax.
|
||||
|
||||
{{< code file=layouts/partials/css.html >}}
|
||||
{{ $opts := dict "use" "autoprefixer postcss-color-alpha" }}
|
||||
{{ with resources.Get "css/main.css" | postCSS $opts }}
|
||||
<link rel="stylesheet" href="{{ .RelPermalink }}">
|
||||
{{ end }}
|
||||
{{< /code >}}
|
||||
|
||||
## Check Hugo environment
|
||||
|
||||
The current Hugo environment name (set by `--environment` or in configuration or OS environment) is available in the Node context, which allows constructs like this:
|
||||
|
||||
{{< code file=postcss.config.js >}}
|
||||
module.exports = {
|
||||
plugins: [
|
||||
require('autoprefixer'),
|
||||
...process.env.HUGO_ENVIRONMENT === 'production'
|
||||
? [purgecss]
|
||||
: []
|
||||
]
|
||||
}
|
||||
{{< /code >}}
|
104
docs/content/en/hugo-pipes/postprocess.md
Executable file
104
docs/content/en/hugo-pipes/postprocess.md
Executable file
@@ -0,0 +1,104 @@
|
||||
---
|
||||
title: PostProcess
|
||||
description: Allows delaying of resource transformations to after the build.
|
||||
categories: [asset management]
|
||||
keywords: []
|
||||
menu:
|
||||
docs:
|
||||
parent: hugo-pipes
|
||||
weight: 50
|
||||
weight: 50
|
||||
action:
|
||||
aliases: []
|
||||
returnType: postpub.PostPublishedResource
|
||||
signatures: [resources.PostProcess RESOURCE]
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
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`).
|
||||
|
||||
A prime use case for this is [CSS purging with PostCSS](#css-purging-with-postcss).
|
||||
|
||||
There are currently two limitations to this:
|
||||
|
||||
1. This only works in `*.html` templates (i.e. templates that produces HTML files).
|
||||
2. You cannot manipulate the values returned from the resource's methods. E.g. the `upper` in this example will not work as expected:
|
||||
|
||||
```go-html-template
|
||||
{{ $css := resources.Get "css/main.css" }}
|
||||
{{ $css = $css | resources.PostCSS | minify | fingerprint | resources.PostProcess }}
|
||||
{{ $css.RelPermalink | upper }}
|
||||
```
|
||||
|
||||
## CSS purging with PostCSS
|
||||
|
||||
{{% 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 some examples.
|
||||
{{% /note %}}
|
||||
|
||||
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).
|
||||
|
||||
{{< code-toggle file=hugo >}}
|
||||
[build.buildStats]
|
||||
enable = true
|
||||
{{< /code-toggle >}}
|
||||
|
||||
See the [configure build] documentation for details and options.
|
||||
|
||||
[configure build]: /getting-started/configuration/#configure-build
|
||||
|
||||
`postcss.config.js`
|
||||
|
||||
```js
|
||||
const purgecss = require('@fullhuman/postcss-purgecss')({
|
||||
content: [ './hugo_stats.json' ],
|
||||
defaultExtractor: (content) => {
|
||||
let els = JSON.parse(content).htmlElements;
|
||||
return els.tags.concat(els.classes, els.ids);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
plugins: [
|
||||
...(process.env.HUGO_ENVIRONMENT === 'production' ? [ purgecss ] : [])
|
||||
]
|
||||
};
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```go-html-template
|
||||
{{ $css := resources.Get "css/main.css" }}
|
||||
{{ $css = $css | resources.PostCSS }}
|
||||
{{ if hugo.IsProduction }}
|
||||
{{ $css = $css | minify | fingerprint | resources.PostProcess }}
|
||||
{{ end }}
|
||||
<link href="{{ $css.RelPermalink }}" rel="stylesheet" />
|
||||
```
|
||||
|
||||
## Hugo environment variables available in PostCSS
|
||||
|
||||
These are the environment variables Hugo passes down to PostCSS (and Babel), which allows you do do `process.env.HUGO_ENVIRONMENT === 'production' ? [autoprefixer] : []` and similar:
|
||||
|
||||
PWD
|
||||
: The absolute path to the project working directory.
|
||||
|
||||
HUGO_ENVIRONMENT
|
||||
: The value e.g. set with `hugo -e production` (defaults to `production` for `hugo` and `development` for `hugo server`).
|
||||
|
||||
HUGO_PUBLISHDIR
|
||||
: {{< new-in 0.109.0 >}} 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 this and similar:
|
||||
|
||||
```js
|
||||
let tailwindConfig = process.env.HUGO_FILE_TAILWIND_CONFIG_JS || './tailwind.config.js';
|
||||
```
|
34
docs/content/en/hugo-pipes/resource-from-string.md
Executable file
34
docs/content/en/hugo-pipes/resource-from-string.md
Executable file
@@ -0,0 +1,34 @@
|
||||
---
|
||||
title: FromString
|
||||
linkTitle: Resource from string
|
||||
description: Creates a resource from a string.
|
||||
categories: [asset management]
|
||||
keywords: []
|
||||
menu:
|
||||
docs:
|
||||
parent: hugo-pipes
|
||||
weight: 110
|
||||
weight: 110
|
||||
action:
|
||||
aliases: []
|
||||
returnType: resource.Resource
|
||||
signatures: [resources.FromString TARGETPATH STRING]
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
It is possible to create a resource directly from the template using `resources.FromString` which takes two arguments, the target path for the created resource and the given content string.
|
||||
|
||||
The result is cached using the target path as the cache key.
|
||||
|
||||
The following example creates a resource file containing localized variables for every project's languages.
|
||||
|
||||
```go-html-template
|
||||
{{ $string := (printf "var rootURL = '%s'; var apiURL = '%s';" (absURL "/") (.Param "API_URL")) }}
|
||||
{{ $targetPath := "js/vars.js" }}
|
||||
{{ $vars := $string | resources.FromString $targetPath }}
|
||||
{{ $global := resources.Get "js/global.js" | resources.Minify }}
|
||||
|
||||
<script src="{{ $vars.Permalink }}"></script>
|
||||
<script src="{{ $global.Permalink }}"></script>
|
||||
```
|
38
docs/content/en/hugo-pipes/resource-from-template.md
Executable file
38
docs/content/en/hugo-pipes/resource-from-template.md
Executable file
@@ -0,0 +1,38 @@
|
||||
---
|
||||
title: ExecuteAsTemplate
|
||||
linkTitle: Resource from template
|
||||
description: Creates a resource from a template
|
||||
categories: [asset management]
|
||||
keywords: []
|
||||
menu:
|
||||
docs:
|
||||
parent: hugo-pipes
|
||||
weight: 120
|
||||
weight: 120
|
||||
action:
|
||||
aliases: []
|
||||
returnType: resource.Resource
|
||||
signatures: [resources.ExecuteAsTemplate TARGETPATH CONTEXT RESOURCE]
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
In order to use Hugo Pipes function on an asset file containing Go Template magic the function `resources.ExecuteAsTemplate` must be used.
|
||||
|
||||
The function takes three arguments: the target path for the created resource, the template context, and the resource object. The target path is used to cache the result.
|
||||
|
||||
```go-html-template
|
||||
// assets/sass/template.scss
|
||||
$backgroundColor: {{ .Param "backgroundColor" }};
|
||||
$textColor: {{ .Param "textColor" }};
|
||||
body{
|
||||
background-color:$backgroundColor;
|
||||
color: $textColor;
|
||||
}
|
||||
// [...]
|
||||
```
|
||||
|
||||
```go-html-template
|
||||
{{ $sassTemplate := resources.Get "sass/template.scss" }}
|
||||
{{ $style := $sassTemplate | resources.ExecuteAsTemplate "main.scss" . | resources.ToCSS }}
|
||||
```
|
213
docs/content/en/hugo-pipes/transpile-sass-to-css.md
Normal file
213
docs/content/en/hugo-pipes/transpile-sass-to-css.md
Normal file
@@ -0,0 +1,213 @@
|
||||
---
|
||||
title: ToCSS
|
||||
linkTitle: Transpile Sass to CSS
|
||||
description: Transpile Sass to CSS.
|
||||
categories: [asset management]
|
||||
keywords: []
|
||||
menu:
|
||||
docs:
|
||||
parent: hugo-pipes
|
||||
returnType: resource.Resource
|
||||
weight: 30
|
||||
weight: 30
|
||||
action:
|
||||
aliases: [toCSS]
|
||||
returnType: resource.Resource
|
||||
signatures: ['resources.ToCSS [OPTIONS] RESOURCE']
|
||||
toc: true
|
||||
aliases: [/hugo-pipes/transform-to-css/]
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
Transpile Sass to CSS using the LibSass transpiler included in Hugo's extended edition, or [install Dart Sass](#dart-sass) to use the latest features of the Sass language.
|
||||
|
||||
```go-html-template
|
||||
{{ $opts := dict "transpiler" "libsass" "targetPath" "css/style.css" }}
|
||||
{{ with resources.Get "sass/main.scss" | toCSS $opts | minify | fingerprint }}
|
||||
<link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
|
||||
{{ end }}
|
||||
```
|
||||
|
||||
Sass has two forms of syntax: [SCSS] and [indented]. Hugo supports both.
|
||||
|
||||
[scss]: https://sass-lang.com/documentation/syntax#scss
|
||||
[indented]: https://sass-lang.com/documentation/syntax#the-indented-syntax
|
||||
|
||||
## Options
|
||||
|
||||
transpiler
|
||||
: (`string`) The transpiler to use, either `libsass` (default) or `dartsass`. Hugo's extended edition includes the LibSass transpiler. To use the Dart Sass transpiler, see the [installation instructions](#dart-sass) below.
|
||||
|
||||
targetPath
|
||||
: (`string`) If not set, the transformed resource's target path will be the original path of the asset file with its extension replaced by `.css`.
|
||||
|
||||
vars {{< new-in 0.109.0 >}}
|
||||
: (`map`) A map of key/value pairs that will be available in the `hugo:vars` namespace. Useful for [initializing Sass variables from Hugo templates](https://discourse.gohugo.io/t/42053/).
|
||||
|
||||
```scss
|
||||
// LibSass
|
||||
@import "hugo:vars";
|
||||
|
||||
// Dart Sass
|
||||
@use "hugo:vars" as v;
|
||||
```
|
||||
|
||||
outputStyle
|
||||
: (`string`) Output styles available to LibSass include `nested` (default), `expanded`, `compact`, and `compressed`. Output styles available to Dart Sass include `expanded` (default) and `compressed`.
|
||||
|
||||
precision
|
||||
: (`int`) Precision of floating point math. Not applicable to Dart Sass.
|
||||
|
||||
enableSourceMap
|
||||
: (`bool`) If `true`, generates a source map.
|
||||
|
||||
sourceMapIncludeSources {{< new-in 0.108.0 >}}
|
||||
: (`bool`) If `true`, embeds sources in the generated source map. Not applicable to LibSass.
|
||||
|
||||
includePaths
|
||||
: (`slice`) A slice of paths, relative to the project root, that the transpiler will use when resolving `@use` and `@import` statements.
|
||||
|
||||
```go-html-template
|
||||
{{ $opts := dict
|
||||
"transpiler" "dartsass"
|
||||
"targetPath" "css/style.css"
|
||||
"vars" site.Params.styles
|
||||
"enableSourceMap" (not hugo.IsProduction)
|
||||
"includePaths" (slice "node_modules/bootstrap/scss")
|
||||
}}
|
||||
{{ with resources.Get "sass/main.scss" | toCSS $opts | minify | fingerprint }}
|
||||
<link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
|
||||
{{ end }}
|
||||
```
|
||||
|
||||
## Dart Sass
|
||||
|
||||
The extended version of Hugo includes [LibSass] to transpile Sass to CSS. In 2020, the Sass team deprecated LibSass in favor of [Dart Sass].
|
||||
|
||||
Use the latest features of the Sass language by installing Dart Sass in your development and production environments.
|
||||
|
||||
### Installation overview
|
||||
|
||||
Dart Sass is compatible with Hugo v0.114.0 and later.
|
||||
|
||||
If you have been using Embedded Dart Sass[^1] with Hugo v0.113.0 and earlier, uninstall Embedded Dart Sass, then install Dart Sass. If you have installed both, Hugo will use Dart Sass.
|
||||
|
||||
If you install Hugo as a [Snap package] there is no need to install Dart Sass. The Hugo Snap package includes Dart Sass.
|
||||
|
||||
[^1]: In 2023, the Sass team deprecated Embedded Dart Sass in favor of Dart Sass.
|
||||
|
||||
### Installing in a development environment
|
||||
|
||||
When you install Dart Sass somewhere in your PATH, Hugo will find it.
|
||||
|
||||
OS|Package manager|Site|Installation
|
||||
:--|:--|:--|:--
|
||||
Linux|Homebrew|[brew.sh]|`brew install sass/sass/sass`
|
||||
Linux|Snap|[snapcraft.io]|`sudo snap install dart-sass`
|
||||
macOS|Homebrew|[brew.sh]|`brew install sass/sass/sass`
|
||||
Windows|Chocolatey|[chocolatey.org]|`choco install sass`
|
||||
Windows|Scoop|[scoop.sh]|`scoop install sass`
|
||||
|
||||
You may also install [prebuilt binaries] for Linux, macOS, and Windows.
|
||||
|
||||
Run `hugo env` to list the active transpilers.
|
||||
|
||||
### Installing in a production environment
|
||||
|
||||
For [CI/CD] deployments (e.g., GitHub Pages, GitLab Pages, Netlify, etc.) you must edit the workflow to install Dart Sass before Hugo builds the site[^2]. Some providers allow you to use one of the package managers above, or you can download and extract one of the prebuilt binaries.
|
||||
|
||||
[^2]: You do not have to do this if (a) you have not modified the assets cache location, and (b) you have not set `useResourceCacheWhen` to `never` in your [site configuration], and (c) you add and commit your resources directory to your repository.
|
||||
|
||||
#### GitHub Pages
|
||||
|
||||
To install Dart Sass for your builds on GitHub Pages, add this step to the GitHub Pages workflow file:
|
||||
|
||||
```yaml
|
||||
- name: Install Dart Sass
|
||||
run: sudo snap install dart-sass
|
||||
```
|
||||
|
||||
If you are using GitHub Pages for the first time with your repository, GitHub provides a [starter workflow] for Hugo that includes Dart Sass. This is the simplest way to get started.
|
||||
|
||||
#### GitLab Pages
|
||||
|
||||
To install Dart Sass for your builds on GitLab Pages, the `.gitlab-ci.yml` file should look something like this:
|
||||
|
||||
```yaml
|
||||
variables:
|
||||
HUGO_VERSION: 0.122.0
|
||||
DART_SASS_VERSION: 1.70.0
|
||||
GIT_DEPTH: 0
|
||||
GIT_STRATEGY: clone
|
||||
GIT_SUBMODULE_STRATEGY: recursive
|
||||
TZ: America/Los_Angeles
|
||||
image:
|
||||
name: golang:1.20-buster
|
||||
pages:
|
||||
script:
|
||||
# Install Dart Sass
|
||||
- curl -LJO https://github.com/sass/dart-sass/releases/download/${DART_SASS_VERSION}/dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz
|
||||
- tar -xf dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz
|
||||
- cp -r dart-sass/* /usr/local/bin
|
||||
- rm -rf dart-sass*
|
||||
# Install Hugo
|
||||
- curl -LJO https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.deb
|
||||
- apt install -y ./hugo_extended_${HUGO_VERSION}_linux-amd64.deb
|
||||
- rm hugo_extended_${HUGO_VERSION}_linux-amd64.deb
|
||||
# Build
|
||||
- hugo --gc --minify
|
||||
artifacts:
|
||||
paths:
|
||||
- public
|
||||
rules:
|
||||
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
|
||||
```
|
||||
|
||||
#### Netlify
|
||||
|
||||
To install Dart Sass for your builds on Netlify, the `netlify.toml` file should look something like this:
|
||||
|
||||
```toml
|
||||
[build.environment]
|
||||
HUGO_VERSION = "0.122.2"
|
||||
DART_SASS_VERSION = "1.70.0"
|
||||
TZ = "America/Los_Angeles"
|
||||
|
||||
[build]
|
||||
publish = "public"
|
||||
command = """\
|
||||
curl -LJO https://github.com/sass/dart-sass/releases/download/${DART_SASS_VERSION}/dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz && \
|
||||
tar -xf dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz && \
|
||||
rm dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz && \
|
||||
export PATH=/opt/build/repo/dart-sass:$PATH && \
|
||||
hugo --gc --minify \
|
||||
"""
|
||||
```
|
||||
|
||||
### Example
|
||||
|
||||
To transpile with Dart Sass, set `transpiler` to `dartsass` in the options map passed to `resources.ToCSS`. For example:
|
||||
|
||||
```go-html-template
|
||||
{{ $opts := dict "transpiler" "dartsass" "targetPath" "css/style.css" }}
|
||||
{{ with resources.Get "sass/main.scss" | toCSS $opts | minify | fingerprint }}
|
||||
<link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
|
||||
{{ end }}
|
||||
```
|
||||
|
||||
### Miscellaneous
|
||||
|
||||
If you build Hugo from source and run `mage test -v`, the test will fail if you install Dart Sass as a Snap package. This is due to the Snap package's strict confinement model.
|
||||
|
||||
[brew.sh]: https://brew.sh/
|
||||
[chocolatey.org]: https://community.chocolatey.org/packages/sass
|
||||
[ci/cd]: https://en.wikipedia.org/wiki/CI/CD
|
||||
[dart sass]: https://sass-lang.com/dart-sass
|
||||
[libsass]: https://sass-lang.com/libsass
|
||||
[prebuilt binaries]: https://github.com/sass/dart-sass/releases/latest
|
||||
[scoop.sh]: https://scoop.sh/#/apps?q=sass
|
||||
[site configuration]: /getting-started/configuration/#configure-build
|
||||
[snap package]: /installation/linux/#snap
|
||||
[snapcraft.io]: https://snapcraft.io/dart-sass
|
||||
[starter workflow]: https://github.com/actions/starter-workflows/blob/main/pages/hugo.yml
|
Reference in New Issue
Block a user