3

Say, I have the following JavaScript module using Vue:

import Vue from "./vue/vue.esm.browser.js";

const app = new Vue({
    el: '#app',
    data: {
        message: 'Hello, world!',
    }
});

// Custom function for calling by the button
function changeMessage() {
    app.message = 'Hello from button!';
}

Now I refer to this module:

<script src="js/site.js" type="module"></script>

Then I try to call changeMessage:

<button onclick="changeMessage();">Press me</button>

However, I get the following error in console:

Uncaught ReferenceError: changeMessage is not defined at HTMLButtonElement.onclick

Moreover, in Visual Studio I don't even get it in IntelliSense. When I remove type="module", then everything works fine. How to make html see the module functions?

JohnyL
  • 6,894
  • 3
  • 22
  • 41

1 Answers1

4

You can define the function on the global window object:

<script type="module">

  window.greet = function () {
    alert('Hello')
  }

</script>

<button onclick="greet()">Hello</button>
Decade Moon
  • 32,968
  • 8
  • 81
  • 101
  • I've updated my answer to demonstrate how it should work. If it isn't working for you, then there must be something else you're doing. Can you include a snippet? – Decade Moon Nov 02 '19 at 12:11
  • You won't believe it, but if I rename file `site.js` to some other name (say, `site2.js`), then the code works! Does name `site.js` have special meaning? – JohnyL Nov 02 '19 at 13:20
  • I figured it out that this behavior is due to browser caching. I just took a look at JS file that browser loads - and it was outdated file. That's it! – JohnyL Nov 02 '19 at 13:36
  • In any case, you should still learn about import/export if you actually want to make use of modules. – Kalnode Nov 02 '19 at 13:57