Use functions defined in ES6 module directly in html

Each module has its own scope. They are not sharing the global scope like “normal” scripts do. That means hello is only accessible inside the main.js module/file itself.

If you explicitly want to create a global variable, you can achieve that by creating a property on the global object, window:

function hello()
{
    console.log(mod());
}
window.hello = hello;

See also Define global variable in a JavaScript function


Having said that, it’s good practice to avoid global variables. Instead you can restructure the HTML to load the modules after the button was created and bind the event handler via JavaScript:

<!DOCTYPE html>
<html>
    <body>
        <button name="next-button">Obi-Wan abandons the high ground to salute you</button>
        <script type="module" src="https://stackoverflow.com/questions/53630310/module.js"></script>
        <script type="module" src="main.js"></script>
    </body>
</html>

and

import { mod } from './module.js';

function hello()
{
    console.log(mod());
}
document.querySelector('button').addEventListener('click', hello);

Leave a Comment