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
exportkeyword and import them in other files using theimportkeyword
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 nameWe 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 itemsWe can also set a custom name for the imports by using the
askeyword
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
Last updated