Esbuild, global module and Uncaught ReferenceError

Advertisements

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:

<!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.

Leave a ReplyCancel reply