Creating a NPM package and deploying it into https://www.npmjs.com

Introduction 

In this blog, I’m going to share how to create npm packages for common functionality and deploy them to https://www.npmjs.com/package

Before we start, let’s set up the pre-requisites.

Step 1: Create an account in npmjs.com (https://www.npmjs.com/signup)

 
 
 
Step 2: Now navigate to the development machine and create a folder and prepare package.js and index.js files for a sample code snippet
 
 
Step 3: Log into npm using vs code terminal console
 
 
 
 
Step 4: Let us create an index.js file as a package source code. For testing purposes, will add very basic functions to calculate a circle, as below:
  1. /* 
  2. JavaScript program to calculate the area and perimeter of a circle 
  3. */  
  4. // behaviour for our module  
  5. function area(data){  
  6.      return  Math.PI * data * data;  
  7.  }  
  8.    
  9.  function perimeter(data){  
  10.      return 2*Math.PI * data;  
  11.  }  
  12.    
  13.  // export to other modules  
  14.  exports.area = area;  
  15.  exports.perimeter = perimeter;  
Step 5: Let's a have look at package.json file & create npm package for above code and publish it to npmjs
 
 
Step 6: Let's publish the above code using the below command 
 
  1. npm publish  
  
 
 Step 7: Now let's verify the package in https://www.npmjs.com/ portal
 
 
If you wish to update the same package, simply change the version and run the same command  
 
 
Its time to test our package in any client-side application. Copy the npm command from the portal as below: 
 
 
 
Step 8: Install the package in our test application
 
 
Let us check in a project file
  
Let's include the package reference and call the test methods
 
 
Conclusion
 
We can create common functionalities like log file, collection filters, common calculations under certain npm packages and we can deploy them in NPM packages