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

Esbuild, global module and Uncaught ReferenceError

I have created a new src/index.js script like this:

export function myFunction() {
  alert("Hello!")
}

I built it using esbuild (0.18.6) with the following configuration:

const esbuild = require('esbuild');

esbuild.build({
  entryPoints: ['./src/index.js'],
  outfile: './dist/index.js',
  bundle: true,
  sourcemap: 'external',
  minify: true,
  globalName: 'xyz',
  loader: {
    '.js': 'jsx'
  }
}).catch(() => process.exit(1));

I’m calling this script inside an HTML file:

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

<!DOCTYPE html>
<html>
  <head>
    <script src="./dist/index.js" defer></script>
  </head>
  <body>
    <button onClick="xyz.myFunction()">Hello</button> <!-- CORRECT. It display the alert message. -->

    <script>
      xyz.myFunction(); /* Error: Uncaught ReferenceError: xyz is not defined */
    </script>
  </body>
</html>

When I run xyz.myFunction() inside the browser (Chrome 114), it executes correctly. However, when it is called within the script tag, I receive the error: "Uncaught ReferenceError: xyz is not defined". How can I solve this issue? Thank you very much.

Edited: I solved it by removing the ‘defer’ attribute within the script tag.

>Solution :

Your first script element uses the defer attribute:

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

But your other script element tries to access xyz during the parse phase, which is before the first script will have been executed.

Don’t defer the first script until after you need it.


I recommend calling your function directly and using addEventListener for event binding inside your bundled script instead of making xyz a global and using onclick attributes and second <script> elements.

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