Modules
Modules are reusable pieces of code in a file that can be exported and then imported for use in another file, which allows the creation of programs whose components can be separated, used individually, and recombined to create a complete system.
We can export modules using the
export
keyword and import them in other files using theimport
keyword
export function add(a, b) { // Exporting functions
return a + b;
}
import { add } from './math.js'; // We define the path of the external file
const add = require('./math.js'); // Or using Node.js syntax
console.log(add(2, 3)); // Exports are saved with the same name
We can also do multiple exports and imports at the same time, and export variables too
function add(a, b) {
return a + b;
}
function mult(a, b) {
return a * b;
}
let pi = 3.14; // Exporting a variable
export { add, mult, pi }; // Exporting multiple items
import { add, mult, pi } from './math.js'; // Importing multiple functions
console.log(add(2, 3));
console.log(mult(2, 3));
console.log(pi);
We can also set a custom name for the imports by using the
as
keyword
function adding(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
export { adding, multiply }; // Export the variables with their name
import { adding as add, multiply as mult } from './math.js'; // Using custom names
console.log(add(2, 3)); // Calling by the changed names
console.log(mult(2, 3));
We can also define a default export, which is a way to specify a single item as the main thing a module provides. This value can be imported without using curly braces in the importing file, and any name can be chosen when importing it
function add(a, b) {
return a + b;
}
function mult(a, b) {
return a * b;
}
export default add; // Exporting multiple items
import addition from './math.js'; // Importing the default item
console.log(addition(4, 3));
Last updated