JS file can't be found (404) when in /assets/js

It is my understanding that a JS file should be put into /assets/js/file.js, because this way it can get minified and fingerprinted (https://gohugo.io/hugo-pipes/minification/).

I did so, my file is in /asses/js/file.js.
I’m using it in a partial like this:

{{ $js := resources.Get "js/klaro.js" }}
{{ $file := $js | resources.Minify }}
<script defer type="application/javascript" src="{{ $file | relURL }}"></script>

But the file can’t be found (404 error). Obviously I’m suspecting some issue with the path. That’s why I tried several other things:

  1. Using absURL instead of relURL
  2. Referencing the file without minification (
  3. Using the “assets/” prefix in the path examples above
  4. Putting the file into static/js/

Nothing of this worked, except when I put the JS file into static/img. Then this worked:

Can anybody tell me

  1. Why is the file found when being in /static/img, but not in /static/js?
  2. How do I correctly use a js file in /assets?

Maybe the config is relevant as well:

    baseURL = "http://my-website"

Thanks a lot!

Is there a value for the assetsDir parameter in your config?
OR
Are you using Hugo modules and have mounted a directory other than the default /assets/?

If you were able to use resources.Get "/static/img/klaro.js" it seems that you have set static/img as the assetsDir because the method resourses.Get only works for files under the assetsDir.

If the above does not help, you need to share your project for us to see the full context.

See doc: Hugo Pipes | Hugo

Assets will only be published (to /public ) if .Permalink or .RelPermalink is used.

I don’t know if it is a typo, but I do not see you referencing .Permalink. If you are and it still is not working, you need to show us your site code.

2 Likes

Thank you very much for helping me out so fast! I was missing the Permalink.

Working code:
{{ $js := resources.Get “js/klaro.js” }}
{{ $file := $js | resources.Minify }}
… src="{{ $file.Permalink }}"

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