Retrieve generated resource file path for use with a Service Worker

Hi,

I currently have a Gulp setup that runs Hugo, followed by Webpack for TypeScript support. The stylesheet is handled by Hugo. The problem I’m facing is that I can’t think of an easy way to import the generated stylesheet into my serviceworker.js for caching, due to it being fingerprinted and having a hash in its name.

My first thought was to use node to generate a .json by reading from the dist folder and looking for the last modified stylesheet. This .json file could be then imported into my serviceworker.js, allowing me to cache the file.

I noticed that there is a .json file inside of the resources/_gen/ directory, containing the name, that could perhaps be of help, but I’m not sure whether this is meant to be private?

Any ideas on how to tackle this, perhaps in a more idiomatic way to Hugo?

Put the resource generation in a partial, then template serviceworker.js so that you can get the value:

{{$resource := partialCached "stylesheet" .}}
{{with $resource}}
{{.RelPermalink}}
{{end}}

Additionally, you can get the stylesheet inline by doing:

{{$resource := partialCached "stylesheet" .}}
{{$resource.Content | safeHTML}}

To fingerprint it:

{{$resource := partialCached "stylesheet" .}}
{{$resource = $resource | fingerprint}}
{{with $resource}}
...
{{end}}

See:

1 Like

Using _gen sounds like a bad idea.

What I would suggest you do is to create a JSON file as part of the Hugo build and dump the relevant resources into this file (use $css.RelPermalink).

2 Likes

Thank you @b_rad and @bep! I’m getting something that works now! :slight_smile:

This is the current setup.

// assets/templates/cache.json
{
    "data": [
    {{- range $index, $section := .Site.Sections -}}
        {{- if ne (add $index 1) (len .Site.Sections) -}}
        {{- printf "\"%s\"," $section.RelPermalink -}}
        {{- else -}}
        {{- printf "\"%s\"" $section.RelPermalink -}}
        {{- end -}}
    {{- end -}}
    ]
}
// layouts/_default/baseof.html
// <--snip-->
{{ $cacheTemplate := resources.Get "templates/cache.json" }}
{{ $cache := $cacheTemplate | resources.ExecuteAsTemplate "./../cache.json" . }}
{{- substr $cache.Permalink 0 0 -}}
// dist/cache.json
{
    "data": ["/journal/","/work/"]
}

It seems to work so far, but I’ll continue working on it and trying to pass in the resources tomorrow, many thanks so far! :slight_smile: