How can we use import and export module in JavaScript

In JavaScript, Modules are basically libraries which are included in the given program. We can connect two JavaScript programs together to call the functions written in one program without writing the body of the functions itself in another program.

  1. Importing a library: It means include a library in a program so that use the function is defined in that library. For this, use ‘require’ function in which pass the library name with its relative path. Suppose a library is made in the same folder with file name library.js, then include the file by using require function:
const lib = require('./library') 
which will return a reference to that library. Now if there is an area function defined in the library, then use it as lib.area().

2. Exporting a library: There is a special object in JavaScript called module.exports. When some program include or import this module (program), this object will be exposed.

For Eg: Exporting Module Example:

let area = function (length, breadth) {
        let a = length * breadth;
        console.log('Area of the rectangle is ' + a + ' square unit');
    }
      
    let perimeter = function (length, breadth) {
        let p = 2 * (length + breadth);
        console.log('Perimeter of the rectangle is ' + p + ' unit');
    }
      
    module.exports = {
        area,
        perimeter
    }

Importing Module Example:

  const lib = require('./library'); 
    // " ./ " is used if both the files are in the same folder.
    let length = 10;
    let breadth = 5;
  
    lib.area(length, breadth);
    lib.perimeter(length, breadth);

Output:

Area of the rectangle is 50 square unit
Perimeter of the rectangle is 30 unit

Leave a comment

Your email address will not be published. Required fields are marked *