How to add a JavaScript file to another JavaScript file

Overview

We can include a JavaScript file in another JavaScript file using the import and export statements.

Starting from ES6, JavaScript introduced the import and export statements to use variables, classes, functions, and so on, across multiple JavaScript files.

Let's see an example to understand how to use the import and export statements, in the code snippet below.

Example

index.js
example.js
// creating a function
const greet = () => {
console.log("Hello World!")
}
// exporting the greet() function
// to be used in other JS files
export {
greet
}

Explanation

In the file example.js,

  • Line 2: We create a function greet() that prints Hello World! on the console.
  • Lines 8–10: We export the function greet() so that it can be used in other JavaScript files.

In the file index.js,

  • Line 2: We import the file example.js.
  • Line 5: We invoke the function greet() defined in the file example.js.

Output

The export statement will export the function greet(), to be used in other JavaScript files and the import statement will include the code exported (in this case, the function greet()) from the file example.js.

Thus, when we run the code above, we see Hello World! on the console.

Free Resources