Functions from Hugo-built Javascript are not available in html


I am planning to move some of my previously static scripts to assets because I need to pass in some parameters in the future.
These script contain some function definitions which used as onclick handlers further down in the html. This worked perfectly fine when loading them from static/js with a script tag.

But after moving them and building the resource

{{ $js := resource.Get "js/script.js | js.Build (dict "params" (dict "p1" "v1" "p2" "v2") "target" "es2015")
<script src="{{ $js.RelPermalink }}" type="text/javascript"></script>

I get errors in the javascript console: ReferenceError: Can’t find variable: myfunction

Am I missing something?

PS: I can assign the functions as click event handlers inside the script, this works fine, I’m wondering, however, why it does not work from inside the html.



Yes, JS bundler (js.Build) will bundle your script into it’s own local scope (not exposed to global window). This is why you cannot access function from outside the script. if you want to make your function accessible from outside, you can export it to window object.

// Inside your script.js
window.my_function = my_function
// Browser Devtools
my_function() //Accessible

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