Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 module "Uncaught ReferenceError: function is not defined at HTMLButtonElement.onclick"

I am trying ES6 module in google chrome. I would like to launch an alert() (in an imported function) when i click on the button.

js/notification.js is well loaded but when I click on the button I get an error:

Uncaught ReferenceError: createNotification is not defined at HTMLButtonElement.onclick ((index):24) <- line of the button in index.html

index.html

<head>
    <script type="module" src="js/main.js"></script>
</head>
<body>
    <section id="container">
       <button type="error" onclick="createNotification()">Create</button>
    </section>
</body>

js/main.js

import {createNotification} from './notification.js';

js/notification.js

export function createNotification(type){
    alert();
}
like image 825
artless boy Avatar asked Jan 31 '18 06:01

artless boy


1 Answers

Functions used in onxyz-attribute-style handlers must be globals (it's one of the many reasons not to use them). Your function isn't a global, it's local to the module in which you're importing it. (Remember: Your main script is a module too; if it weren't, you couldn't use import in it.)

You could make it a global by assigning to a window property:

window.createNotification = createNotification;

but it would be much better to use modern event handling:

document.querySelector("#container button").addEventListener("click", createNotification);

Live example on plnkr, obviously will only work on cutting-edge browsers with module support.


Side note: As Andreas points out, type="error" isn't valid for button elements. Valid types are button, submit, or reset, with submit being the default. (I've changed it to button in the plnkr.)

like image 96
T.J. Crowder Avatar answered Oct 22 '22 08:10

T.J. Crowder