Modules

What are modules?

Modules in Node.js are reusable pieces of code that can be exported from one program and imported for use in another program.

The advantages of separating code with similar logic into modules

  • easily find, fix, and debug code
  • reuse and recycle defined logic in different parts of our application
  • keep information private and protected from other modules
  • prevent pollution of the global namespace and potential naming collisions

module.exports

We can define a module in one file and make it available for use in another file with 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",
};

Named Export vs Default Export

ES6 provides two ways to export a module from a file: named export and default export.

1. Default Export: (export default)

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;

2. Named Export: (export)

Named exports are useful to export several values based on variable names. During the import, we will be able to use the same name to refer to the corresponding value.

  1. Named exports use the export keyword to export data.
export { student, greeting };
  1. Named exports can be exported as soon as they are declared, by placing the keyword export in front of variable declarations.
export let student = "";
export function greeting() {}
  1. Named exports can be aliased with the as keyword.
let movieName = "";
let ratingScore = function () {};
let year = function () {};

export { movieName as name, ratingScore as rating, year };

require()

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();

import

In ES6, import is a keyword that imports any object, function, or data type.

import Cat from "./cat";
  • The import keyword
  • The keyword Cat: name of the variable
  • from 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.
  1. To import all the exports from a script by using the _ selector: import _ from 'module_name';
import * as Movie from "./moview";

Movie.name;
Movie.rating();
Movie.year();
  1. To import objects stored in a variable, we include the variables in {}:
import {funcA, funcB} as name from 'module_name';

For example

import { specialty, isVegetarian } from "./menu";

console.log(specialty);