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?
asked Nov 2, 2019 at 11:31
JohnyL
7,2045 gold badges27 silver badges48 bronze badges
-
1Look into module imports/exports.Kalnode– Kalnode2019年11月02日 11:38:22 +00:00Commented Nov 2, 2019 at 11:38
-
@MarsAndBack Could you be more specific?JohnyL– JohnyL2019年11月02日 11:46:50 +00:00Commented Nov 2, 2019 at 11:46
-
1as @MarsAndBack stated, you need to understand how to export that function and import when needed. More on this stackoverflow.com/questions/49338193/…Jimish Fotariya– Jimish Fotariya2019年11月02日 12:16:25 +00:00Commented Nov 2, 2019 at 12:16
1 Answer 1
You can define the function on the global window object:
<script type="module">
window.greet = function () {
alert('Hello')
}
</script>
<button onclick="greet()">Hello</button>
answered Nov 2, 2019 at 12:01
Decade Moon
34.4k8 gold badges84 silver badges104 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Decade Moon
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?
JohnyL
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
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! 😆
Kalnode
In any case, you should still learn about import/export if you actually want to make use of modules.
lang-js