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?

3
  • 1
    Look into module imports/exports. Commented Nov 2, 2019 at 11:38
  • @MarsAndBack Could you be more specific? Commented Nov 2, 2019 at 11:46
  • 1
    as @MarsAndBack stated, you need to understand how to export that function and import when needed. More on this stackoverflow.com/questions/49338193/… Commented Nov 2, 2019 at 12:16

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

4 Comments

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?
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?
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! 😆
In any case, you should still learn about import/export if you actually want to make use of modules.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.