0

I have a few JS functions in the main-entry JS file that are called only by HTML menus after user interaction, and obviously esbuild thinks that they are not used, like so:

HTML:

<a id="ndb" onmouseenter="keeptopbar()" onmouseleave="reltopbar()" onclick="askuser('newform')">FORM</a>

script.js:

function askuser(inpv) { 
    var st = "";
    if (inpv === 'newform'){

EDIT: I tried to add "export" on those functions but it didn't work.

Is there an option to include in package.json in order to make esbuild include all functions found in the main-entry JS file, or any other trick?

2
  • 1
    Is using addEventListener not an option?
    – Phix
    Jul 15, 2021 at 17:39
  • I don't think so, I wrote that HTML a few years back and I remember I didn't have that choice -some functions wouldn't work in other ways, everything is in an ...equilibrium to avoid a number of HTML/JS bugs...
    – dllb
    Jul 15, 2021 at 17:43

2 Answers 2

4

You can create the functions as properties of the global object:

window.keeptopbar = function(){
    //...
};

window.reltopbar = function(){
    //...
};

window.askuser = function(inpv){
    //...
};

That way, esbuild's tree shaking won't remove them, and you also make sure the functions are global.

1
  • how would you access one of those functions from inside window.xxx ? I've tried window.xxx.myFunction() and it can't find it. Dec 29, 2021 at 3:12
0

You can try making ESBuild believe these functions are going to be used in your JS. This might work:

if (Math.random() < 0) console.log(askuser);
2
  • Yeah, that's what I was thinking to try right now (not the exact code), maybe there is something even simpler...
    – dllb
    Jul 15, 2021 at 18:08
  • And yet that didn't work. I also tried it directly, without the console.log.
    – dllb
    Jul 15, 2021 at 18:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.