How can I make functions common between assets/js and static/js?

I’m working on AMP project. I have an authorization callback that is defined in static/js (for some unknown reason, the callback should be defined in static/js). How I can make the function defined in assets/js to be visible in static/js?

My main js is included in HTML before that static/js and use this construction

{{ $js := resources.Get "js/custom.js" | js.Build }}
<script src="{{ $js.Permalink }}"></script>

Seems like the code in assets is being executed before the static js file is parsed. Perhaps wrap it in a window.onload? Check whether the scripts are loaded async or deferred? This seems to be a javascript question and I’m no expert. Hope this pushes you along in the right direction.

I feel this is not a javascript issue. js.Build compile all imports and outputs invoked anonymous function. This should broke visibility area.
Before refactor this worked.

So, the problem should be in import on the very top of my custom.js. I started to use js.Build because I have created separate modules in my custom.js and import them in file.

So, I have 2 potential solutions of this:

  1. I need to find option for js.Build, that won’t build all contants of custom.js in invoked anonymous function.
  2. I need to find other solution, how I can import functions in custom.js, without need to js.Build my custom.js in the end

The only way is to share the function window via the global window object, e.g. window.myFunc = function() { console.log('foo').

1 Like

This works when it is assigned in the root of custom.js. Thanks @bep

But I should assign this function in assets/js/utils/a/a.js and want to import it in custom.js. How to?
Before, in afile.js I have defined export of function as

export function a { ... }

and on the very top of customs.js I’ve imported it

import { a } from js/utils/afile

and then I used it.

I’m not totally sure what you want to do do, but …

import { a } from "js/utils/afile"

window.a = a;

Assuming the above is loaded before your static file, a() should be available.

1 Like

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