Modules in Node.js are reusable pieces of code that can be exported from one program and imported for use in another.
The advantages of separating code with similar logic into modules
We can define a module in one file and make it available for use in another file with the module.exports
syntax.
Example:
let Cat = {};
Cat.name = "Butter";
module.exports = Cat;
We can also wrap data and functions in an object and export the object using module.exports
.
In cat.js, we write:
module.exports = {
name: "Butter",
};
ES6 provides two ways to export a module from a file: named export and default export.
Default exports use export default
to export JavaScript objects, functions, and primitive data types.
We can have only one default export per file.
let Cat = {};
Cat.name = "Butter";
export default Cat;
Named exports are useful for exporting several values based on variable names. During the import, we can use the same name to refer to the corresponding value.
export
keyword to export data.export { student, greeting };
export
in front of variable declarations.export let student = "";
export function greeting() {}
as
keyword.let movieName = "";
let ratingScore = function () {};
let year = function () {};
export { movieName as name, ratingScore as rating, year };
require() imports the module for use in the current program.
For example, in introduce.js, we write:
const Cat = require('./cat.js');
function introduce() {
console.log('My cat is: ' + Cat.name;
}
introduce();
In ES6, import
is a keyword that imports any object, function, or data type.
import Cat from "./cat";
import
keywordCat
: name of the variablefrom
specifies where to load the module from.'./cat'
: the name of the module to load. When dealing with local files, we don’t need the extension of the file.import _ from 'module_name';
import * as Movie from "./moview";
Movie.name;
Movie.rating();
Movie.year();
import {funcA, funcB} as name from 'module_name';
For example
import { specialty, isVegetarian } from "./menu";
console.log(specialty);