Merge commit '87de22d7464e239c775fbd48ebce1665d5b1e80d'

This commit is contained in:
Bjørn Erik Pedersen
2023-07-29 11:17:28 +02:00
177 changed files with 1623 additions and 1556 deletions

View File

@@ -1,10 +1,12 @@
---
title: Hugo Pipes Overview
title: Hugo Pipes
linkTitle: Overview
categories: [asset management]
keywords: []
menu:
docs:
parent: pipes
identifier: hugo-pipes-overview
parent: hugo-pipes
weight: 10
weight: 10
---

View File

@@ -5,9 +5,9 @@ categories: [asset management]
keywords: []
menu:
docs:
parent: pipes
weight: 48
weight: 48
parent: hugo-pipes
weight: 70
weight: 70
signature: ["resources.Babel RESOURCE [OPTIONS]", "babel RESOURCE [OPTIONS]"]
---
@@ -22,7 +22,7 @@ Hugo Pipe's Babel requires the `@babel/cli` and `@babel/core` JavaScript package
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 %}}
### Config
### 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.:
@@ -59,7 +59,7 @@ 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 filename + ".map". Input sourcemaps can be read from js.Build and node modules and combined into the output sourcemaps.
: 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

View File

@@ -6,9 +6,9 @@ categories: [asset management]
keywords: []
menu:
docs:
parent: pipes
weight: 60
weight: 60
parent: hugo-pipes
weight: 90
weight: 90
signature: ["resources.Concat TARGET_PATH SLICE_RESOURCES"]
---

View File

@@ -1,14 +1,14 @@
---
title: Fingerprint
linkTitle: Fingerprinting and SRI
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: pipes
weight: 70
weight: 70
parent: hugo-pipes
weight: 100
weight: 100
signature: ["resources.Fingerprint RESOURCE [ALGORITHM]", "fingerprint RESOURCE [ALGORITHM]"]
---

View File

@@ -1,34 +1,34 @@
---
title: Hugo Pipes Introduction
linkTitle: Hugo Pipes
title: Hugo Pipes
linkTitle: Introduction
description: Hugo Pipes is Hugo's asset processing set of functions.
categories: [asset management]
keywords: []
menu:
docs:
parent: pipes
parent: hugo-pipes
weight: 20
weight: 01
weight: 20
toc: true
aliases: [/assets/]
---
## Find Resources in /assets
## Find resources in /assets
This is about the global Resources mounted inside `/assets`. For the `.Page` scoped Resources, see [Page Resources](/content-management/page-resources/).
Note that you can mount any directory into Hugo's virtual `assets` folder using the [Mount Configuration](/hugo-modules/configuration/#module-config-mounts).
Note that you can mount any directory into Hugo's virtual `assets` folder using the [Mount Configuration](/hugo-modules/configuration/#module-configuration-mounts).
| Function | Description |
| ------------- | ------------- |
| `resources.Get` | Get locates the filename given in Hugo's assets filesystem and creates a `Resource` object that can be used for further transformations. See [Get Resource with resources.Get and resources.GetRemote](#get-resource-with-resourcesget-and-resourcesgetremote). |
| `resources.GetRemote` | Same as `Get`, but it accepts remote URLs. See [Get Resource with resources.Get and resources.GetRemote](#get-resource-with-resourcesget-and-resourcesgetremote).|
| `resources.Get` | Get locates the file name given in Hugo's assets filesystem and creates a `Resource` object that can be used for further transformations. See [Get a resource](#get-a-resource). |
| `resources.GetRemote` | Same as `Get`, but it accepts remote URLs. See [Get a resource](#get-a-resource).|
| `resources.GetMatch` | `GetMatch` finds the first Resource matching the given pattern, or nil if none found. See Match for a more complete explanation about the rules used. |
| `resources.Match` | `Match` gets all resources matching the given base path prefix, e.g "*.png" will match all png files. The "*" does not match path delimiters (/), so if you organize your resources in sub-folders, you need to be explicit about it, e.g.: "images/*.png". To match any PNG image anywhere in the bundle you can do "\*\*.png", and to match all PNG images below the images folder, use "images/\*\*.jpg". The matching is case insensitive. Match matches by using the files name with path relative to the file system root with Unix style slashes (/) and no leading slash, e.g. "images/logo.png". See https://github.com/gobwas/glob for the full rules set.|
See the [GoDoc Page](https://pkg.go.dev/github.com/gohugoio/hugo@v0.93.1/tpl/resources) for the `resources` package for an up to date overview of all template functions in this namespace.
## Get Resource with resources.Get and resources.GetRemote
## Get a resource
In order to process an asset with Hugo Pipes, it must be retrieved as a `Resource` using `resources.Get` or `resources.GetRemote`.
@@ -71,7 +71,7 @@ By default, Hugo calculates a cache key based on the `URL` and the `options` (e.
{{ $resource := resource.GetRemote $url (dict "key" $cacheKey) }}
```
### Error Handling
### Error handling
The return value from `resources.GetRemote` includes an `.Err` method that will return an error if the call failed. If you want to just log any error as a `WARNING` you can use a construct similar to the one below.
@@ -87,7 +87,7 @@ The return value from `resources.GetRemote` includes an `.Err` method that will
Note that if you do not handle `.Err` yourself, Hugo will fail the build the first time you start using the `Resource` object.
### Remote Options
### Remote options
When fetching a remote `Resource`, `resources.GetRemote` takes an optional options map as the second argument, e.g.:
@@ -113,15 +113,15 @@ You can also change the request method and set the request body:
)}}
```
### Caching of Remote Resources
### Caching of remote resources
Remote resources fetched with `resources.GetRemote` will be cached on disk. See [Configure File Caches](/getting-started/configuration/#configure-file-caches) for details.
## Copy a Resource
## Copy a resource
{{< new-in "0.100.0" >}}
`resources.Copy` allows you to copy almost any Hugo `Resource` (the one exception is the `Page`), possibly most useful for renaming things:
Use `resources.Copy` to copy a page resource or a global resource. Commonly used to change a resource's published path, `resources.Copy` takes two arguments: the target path relative to the root of the `publishDir` (with or without a leading `/`), and the resource to copy.
```go-html-template
{{ with resources.Get "img/a.jpg" }}
@@ -141,7 +141,7 @@ The target path must be different than the source path, as shown in the example
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
### 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.

View File

@@ -1,14 +1,14 @@
---
title: js.Build
linkTitle: JavaScript Building
linkTitle: JavaScript building
description: Process a JavaScript file with [ESBuild](https://github.com/evanw/esbuild).
categories: [asset management]
keywords: []
menu:
docs:
parent: pipes
weight: 45
weight: 45
parent: hugo-pipes
weight: 60
weight: 60
signature: ["js.Build RESOURCE [OPTIONS]"]
---
@@ -34,7 +34,7 @@ And then in your JS file:
import * as params from '@params';
```
Note that this is meant for small data sets, e.g. config settings. For larger data, please put/mount the files into `/assets` and import them directly.
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.
@@ -91,7 +91,7 @@ format [string]
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 filename + ".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.
: 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
@@ -137,7 +137,7 @@ 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
### 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`.

View File

@@ -6,9 +6,9 @@ categories: [asset management]
keywords: []
menu:
docs:
parent: pipes
weight: 50
weight: 50
parent: hugo-pipes
weight: 80
weight: 80
signature: ["resources.Minify RESOURCE", "minify RESOURCE"]
---

View File

@@ -5,7 +5,7 @@ categories: [asset management]
keywords: []
menu:
docs:
parent: pipes
parent: hugo-pipes
weight: 40
toc: true
weight: 40
@@ -114,7 +114,7 @@ syntax
## Check Hugo environment
The current Hugo environment name (set by `--environment` or in config or OS environment) is available in the Node context, which allows constructs like this:
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 = {

View File

@@ -5,9 +5,9 @@ categories: [asset management]
keywords: []
menu:
docs:
parent: pipes
weight: 39
weight: 39
parent: hugo-pipes
weight: 50
weight: 50
signature: ["resources.PostProcess RESOURCE"]
---
@@ -36,11 +36,17 @@ There are several ways to set up CSS purging with PostCSS in Hugo. If you have a
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).
<!-- TODO (jmm) writeStats => build.buildStats -->
{{< code-toggle file="hugo" >}}
[build]
writeStats = true
[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
@@ -71,7 +77,7 @@ Note that in the example above, the "CSS purge step" will only be applied to the
```
## Hugo Environment variables available in PostCSS
## 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:
@@ -83,7 +89,7 @@ HUGO_ENVIRONMENT (and the alias HUGO_ENV)
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:
```
```text
hugo server --renderToDisk
hugo server --renderStaticToDisk
```

View File

@@ -1,14 +1,14 @@
---
title: FromString
linkTitle: Resource from String
linkTitle: Resource from string
description: Creates a resource from a string.
categories: [asset management]
keywords: []
menu:
docs:
parent: pipes
weight: 90
weight: 90
parent: hugo-pipes
weight: 110
weight: 110
signature: ["resources.FromString TARGET_PATH CONTENT"]
---
@@ -16,6 +16,8 @@ signature: ["resources.FromString TARGET_PATH CONTENT"]
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

View File

@@ -1,14 +1,14 @@
---
title: ExecuteAsTemplate
linkTitle: Resource from Template
linkTitle: Resource from template
description: Creates a resource from a template
categories: [asset management]
keywords: []
menu:
docs:
parent: pipes
weight: 80
weight: 80
parent: hugo-pipes
weight: 120
weight: 120
signature: ["resources.ExecuteAsTemplate TARGET_PATH CONTEXT RESOURCE"]
---
@@ -16,7 +16,7 @@ signature: ["resources.ExecuteAsTemplate TARGET_PATH CONTEXT RESOURCE"]
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 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

View File

@@ -1,58 +0,0 @@
---
title: ToCSS
linkTitle: Transpile Sass to SCSS
description: Transpile Sass to CSS.
categories: [asset management]
keywords: []
menu:
docs:
parent: pipes
weight: 30
weight: 02
signature: ["resources.ToCSS RESOURCE [OPTIONS]", "toCSS RESOURCE [OPTIONS]"]
---
## Usage
Any Sass or SCSS file can be transformed into a CSS file using `resources.ToCSS` which takes two arguments, the resource object and a map of options listed below.
```go-html-template
{{ $sass := resources.Get "sass/main.scss" }}
{{ $style := $sass | resources.ToCSS }}
```
### Options
transpiler [string]
: The `transpiler` to use, valid values are `libsass` (default) and `dartsass`. If you want to use Hugo with Dart Sass you need to download a release binary from [Embedded Dart Sass](https://github.com/sass/dart-sass-embedded/releases) and make sure it's in your PC's `$PATH` (or `%PATH%` on Windows).
targetPath [string]
: If not set, the transformed resource's target path will be the asset file original path with its extension replaced by `.css`.
vars [map]
: Map of key/value pairs that will be available in the `hugo:vars` namespace, e.g. with `@use "hugo:vars" as v;` or (globally) with `@import "hugo:vars";` {{< new-in "0.109.0" >}}
outputStyle [string]
: Default is `nested` (LibSass) and `expanded` (Dart Sass). Other available output styles for LibSass are `expanded`, `compact` and `compressed`. Dart Sass only supports `expanded` and `compressed`.
precision [int]
: Precision of floating point math. **Note:** This option is not supported by Dart Sass.
enableSourceMap [bool]
: When enabled, a source map will be generated.
sourceMapIncludeSources [bool]
: When enabled, sources will be embedded in the generated source map. (Dart Sass only). {{< new-in "0.108.0" >}}
includePaths [string slice]
: Additional SCSS/Sass include paths. Paths must be relative to the project directory.
```go-html-template
{{ $options := (dict "targetPath" "style.css" "outputStyle" "compressed" "enableSourceMap" (not hugo.IsProduction) "includePaths" (slice "node_modules/myscss")) }}
{{ $style := resources.Get "sass/main.scss" | resources.ToCSS $options }}
```
{{% note %}}
Setting `outputStyle` to `compressed` will handle Sass/SCSS files minification better than the more generic [`resources.Minify`](/hugo-pipes/minification).
{{% /note %}}

View File

@@ -0,0 +1,210 @@
---
title: ToCSS
linkTitle: Transpile Sass to CSS
description: Transpile Sass to CSS.
categories: [asset management]
keywords: []
menu:
docs:
parent: hugo-pipes
weight: 30
weight: 30
signature: ["resources.ToCSS RESOURCE [OPTIONS]", "toCSS RESOURCE [OPTIONS]"]
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
{{ $options := dict "transpiler" "libsass" "targetPath" "css/style.css" }}
{{ with resources.Get "sass/main.scss" | toCSS $options | 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
{{ $options := 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 $options | 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.115.1
DART_SASS_VERSION: 1.63.6
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.115.1"
DART_SASS_VERSION = "1.63.6"
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
{{ $options := dict "transpiler" "dartsass" "targetPath" "css/style.css" }}
{{ with resources.Get "sass/main.scss" | toCSS $options | 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