Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to use esbuild with plain javascript

I have two files

// index.js
// ... import some other modules ...
export function test() {
  alert("I'm using some modules");
}

and

<!-- index.html -->
<div onclick="test()">test</div>

I can "bundle" the JS

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

esbuild index.js --outfile=www/main.js --bundle

But how can I use test() from index.html?

>Solution :

As per the documentation:

Specify a global name for the exports:

esbuild index.js --outfile=www/main.js --bundle --global-name=xyz

Then you can access it view:

<div onclick="xyz.test()">test</div>

However! Don’t do the above!

Intrinsic event attributes have not been considered best practise for a couple of decades and have some areas where they give unexpected behaviour.

Use addEventListener instead.

This will remove the need to include --global-name=xyz since you’ll be using your function inside your script and not from another script elsewhere in the HTML document.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading