How to load javascript function in heex script tag

I have a ‘marker_clustering.js’ file in ‘assets/vendor’ directory.
This file defines a constructor function called MarkerClustering and has an export default MarkerClustering directive.

In the ‘app.js’ file, there is an import MarkerClustering from "../vendor/marker_clustering" declaration.

In the ‘root.html.heex’ file, load the ‘app.js’ file as follows:
<script defer phx-track-static type="text/javascript" src={~p"/assets/app.js"} />

In the above situation, if you use the ‘MarkerClustering constructor’ in the script tag of the ‘home.html.heex’ file, the following error will appear in the browser console:
Uncaught ReferenceError: MarkerClustering is not defined

Even if I assign MarkerClustering to windows.MarkerClustering, this problem is not solved.

I wonder what to do in this case.

By default, your JS is bundled by ESBuild, so when you import an ES module it gets bundled up and converted into a function (an IIFE) which is evalulated when the script is loaded. If you open up your browser devtools and have a look at the JS that is actually loaded, you should be able to see all of the Phoenix code and your code bundled up in app.js. Have a look and see if the code you are expecting is in there, and if anything looks wrong.

Also, there’s a typo in your import statement (three dots should be two dots). I don’t think that syntax is valid - is ESBuild raising an error in your terminal during compilation? (Edit your app.js to trigger a recompile and look for errors).

1 Like