I have a simple HTML page, which is importing a JS module as follows:
.. snip
<button onclick="btnClick()">Go!</button>
<script type="module">
import { func1 } from './utils.js'
function btnClick() {
func1()
}
</script>
Clicking the button produces an error: btnClick() is not defined.
Why is this happening? How to bring these functions back into correct scope?
Calling a function using external JavaScript file Js) extension. Once the JavaScript file is created, we need to create a simple HTML document. To include our JavaScript file in the HTML document, we have to use the script tag <script type = "text/javascript" src = "function.
Modules are independent and self-contained chunks of code. You create them by splitting up a larger program into logical parts or dependencies. Modules should be independent, specialized, and reusable. You use the import and export keywords to interchange functionalities between modules in JavaScript.
A script tag having type="module" attribute specifies that it to be considered as a Javascript module. It may be importing other Javascript module(s) inside it and becomes a "top-level" module for the imported modules.
The javascript execution stack has own scope, so, simple and easy solution is, you can assign to window scope your accessible functions like below;
<button onclick="btnClick()">Go!</button>
<script type="module">
import { func1 } from './utils.js'
function btnClick() {
func1()
}
// variable function
window.btnClick = btnClick;
// or anonymous function
window.btnClick = function(youCanSetParams){
func1()
}
</script>
Variable from "module" are not accessible from outside so use type="text/javascript" as
<script type="text/javascript">
function btnClick() {
console.log('here')
}
</script>
<button onclick="btnClick()">Go!</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With