How would you add a javascript Ressource (Branch Bundle) that requires type="module"

  1. I have some javascript next next to my _index.html within a branch.
  2. in my layouts/_default/baseof.html I have this in my head:
{{ range .Resources.Match "**.js"}}
<script src="{{ .Permalink }}"></script>
{{end}}

So, How do you set the script attributes if the resource is of type module or defer it?

<script src="{{ .Permalink }}" type="module"></script>

I might be missing what you are asking for, but the above loads your script as a module.

If you plan to do it “properly” have a look at Javascript Building in Hugo.

If this is about how to match for your Javascript files, you need to show how your content is structured. What you posted should work if the following file structure is there:

/content/some/path/index.md
/content/some/path/a-module.js

In the layout that matches the current section you can then run something like:

{{ with .Resources.Match "**.js"}}
{{ range . }}
<script src="{{ .Permalink }}"></script>
{{ end }}
{{end}}

This will silently continue building if there is no js file in the page bundle.

in my layout, I somehow need to decide how the script needs to be rendered into the page. These three options do exist:

<script src="{{ .Permalink }}" ></script>
<script src="{{ .Permalink }}" defer ></script>
<script src="{{ .Permalink }}" type="module"></script>

And the layout does not know what is needed, but somehow needs to be informed.

Not working pseudo code:

<script {{ with .Params.module }} type="module" {{end}} {{ with .Params.defer}} defer {{end}} src="{{ .Permalink }}"></script>

Each section needs a different javascript resource (or none). /content/some/path/index.md/html is unsing the resource and knows how it needs to be rendered.

So the hopefully better question is. How do I define within my index.html how the resource needs to be rendered?

I’m aware of: Page Resources | Hugo But was not able to use the resources.params to store the information in the index.html and access it in: {{ range .Resources.Match “**.js”}}

I hope the question is better now.

Cant explain, the previously not working pseudo code from above is working now:

with the frontmater:

---
title: "Home"
date: 2021-12-21T15:36:53+01:00
resources:
- src: home.js
  params:
    module: true
    defer: true
---

and the layout:

<script {{ with .Params.module }} type="module" {{end}} {{ with .Params.defer }} defer {{end}} src="{{ .Permalink }}"></script>

I’ll get exactly what I was looking for:

<script type="module" defer src="http://localhost:1313/home/home.js"></script>

I know, it’s not required to defer a type=“module” :wink:

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.