JavaScript Import Function From Another File
In this JavaScript tutorial, you’re going to learn how to import a function from another JavaScript file with 3 simple steps.
- Convert JavaScript File to an ES Module
- Declare & Export A Function
- Import & Call A Function From Another File
STEP #1: Convert JavaScript File to an ES Module
Create an index.html file and include the main.js file inside it using the script tag.
Add the type=”module” attribute to the starting script tag.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Import Function From Another File</title>
</head>
<body>
<script src="main.js" type="module"></script>
</body>
</html>
Adding type=”module” is enabling the browser to handle the JavaScript file as a module and allows the use of ECMAScript module syntax, such as import, export, and, within that file.
Otherwise, it will throw an error: Uncaught SyntaxError: Cannot use import statement outside a module
STEP #2: Declare & Export A Function
Declare the add() function inside the math.js file which will be in the same root level as the main.js and index.html files.
math.js
const add = (a, b) => {
return a + b;
};
export { add };
Finally, export the add() function.
STEP #3: Import & Call A Function From Another File
Import the add() function declared in the math.js file inside the main.js file
main.js
import { add } from "./math.js";
const result = add(2, 4);
console.log(result); // 6
In the above import statement, add() inside the curly braces is the name of the function that I want to import, and “./math.js” is the path to the file containing the function I want to import.
Make sure to provide the correct file path relative to the main.js file.
Once the add() function is imported, call it inside the main.js file.