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.
// creating a functionconst greet = () => {console.log("Hello World!")}// exporting the greet() function// to be used in other JS filesexport {greet}
In the file example.js,
greet() that prints Hello World! on the console.greet() so that it can be used in other JavaScript files.In the file index.js,
example.js.greet() defined in the file example.js.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.