Search code examples
javascriptimportjavascript-import

Functions and class methods not working inside HTML while importing other functions from another file


I have two files , "file1.js" and "file2.js". I'm importing functions from "file1.js" to "file2.js". Importing works, but after import, the code inside "file2.js" doesn't seems to work when I try to call any function or class methods from Html. Eg: Calling a function on a button click.

Is there a way that I can fix it? I'm just trying to separate utility functions and algorithms.. what am i doing worng?

file1.js

// file1.js
export function addNumbers(a, b) {
    return a + b;
}

/* File for Utlity functions */

file2.js

// file2.js
import {addNumbers} from './file1.js';


// Use the imported function
const result = addNumbers(5, 3);
console.log('Imported function result ', result); // Output: 8



// This function will be called from html.

function call_this_function(){
  console.log("function called")
}

// Calling from file itself works Eg:

call_this_function();

// But calling from HTML will cause an error of Reference.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
     <!-- This button will call `call_this_function` from file2.js -->
    <button onclick="call_this_function()">Test Button</button>

    <script type="module" src="file1.js"></script>
    <script type="module" src="file2.js"></script>
</body>
</html>

Here's the error that is popping up when I click the button to show a message.

test/:10 Uncaught ReferenceError: call_this_function is not defined
    at HTMLButtonElement.onclick (test/:10:44)

How can I resolve this issue? What am I doing wrong?


Solution

  • When an script is imported as type='module', the entire file becomes a JavaScript module. The variables & functions declared inside can only be accessed within its scope.

    If you want to use them in global scope, you have to export it to global scope like adding it to window object.

    Eg: window.call_this_function = call_this_function at end of the file2.js will make it work.