Types of module exports

 

modules in node js


Types of module exports

Node js uses a module to distribute logic and increase code readability. with the help of modules, we can increase the speed of our development by just importing the existing module in our project. 
if you have used  node.js, React.js, or any modern-day javascript library then you must know "modules". ideally, we use the "node_modules" folder to store all our modules of that particular project. which keeps our project structure standard and easily understandable. in the same way, we can create our own modules in our project. let's see how we can create and import-export modules.


Benefits of using modules:

  • increase development speed.
  • increase code readability.
  • code reusability.
  • easy to manage code.


Let's see how we can create a module and import-export it wherever we want in code.

First Approach

E.g you have two modules created in a single file like given below.


First .js
function module1(){
return new Promise((resolve,reject)=>{
// apply your logic here
})
}

function module2(){
return new Promise((resolve,reject)=>{
// apply your logic here
})
}

Export

module.exports={module1,module2}

Import

const {module1,module2} = require(‘./first’)


Second Approach


You can export immediately after created modules

module.exports module= ()=>{
return new Promise((resolve,reject)=>{
// apply your logic here
})
}

Import

const module1 = require(‘./first’)

Third Approach

we can also create a class and export the entire class. later we can access functions of exported class
  class Animals{
numberOfLegs(){
//implement your logic here;
return null;
}

numberOfEyes(){
//implement your logic here;
return null;
}

}

Export

module.exports=Animals


Import

const Animals = require(‘./first’)
Animals.numberOfEyes()



 

Post a Comment

0 Comments