ES6 Modules: Undefined onclick function after import

Module creates a scope to avoid name collisions.

Either expose your function to window object

import {hello} from './test.js'

window.hello = hello

Or use addEventListener to bind handler. Demo

<button type="button" id="hello">Click Me</button>
<script type="module">
  import {hello} from './test.js'

  document.querySelector('#hello').addEventListener('click', hello)
</script>

Leave a Comment