Building a js file and calling one of its functions

hi. I’m trying to do some hello world level stuff and I can’t figure it out, please help.

// assets/js/tada.js
export function tada() {
   alert("TADA!!");
}

this one works, as I’m not calling js.Build

//layouts/shortcodes/tada_ok.html
{{ $js := resources.Get "/js/tada.js" }}

<script src="{{ $js.RelPermalink }}"> </script>
<button onclick="tada()">pressme</button>

but if I add the js.Build step …

//layouts/shortcodes/tada_notok.html
{{ $js := resources.Get "/js/tada.js" | js.Build }}

<script src="{{ $js.RelPermalink }}"> </script>
<button onclick="tada()">pressme</button>

… clicking on the button gives me the “tada is not defined” error.

I can see that the compilation did something to my code:

// built /js/tada.js
(() => {
  // <stdin>
  function tada() {
    alert("tada");
  }
})();

What’s happening ?

1 Like

What is looper? Is that a mistake?

yeah sorry it’s a mistake, I renamed some stuff to make it more generic. correcting this right now.

When implemented as a JS module, the function is out-of-scope in the button element’s onclick attribute.

git clone --single-branch -b hugo-forum-topic-47765 https://github.com/jmooring/hugo-testing hugo-forum-topic-47765
cd hugo-forum-topic-47765
hugo server

Thanks a lot! I could not find anything in the documentation about that, did I miss something? If not, it would probably make sense to add a comment about this in js.Build | Hugo

Your question/challenge was really about how JS modules work; nothing specific to Hugo.

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