Creating your own NPM modules

 Creating your own NPM modules

NPM modules or we can say NPM packages are a very vital part of any Node.js based project. In this article, we’ll practically learn how to create and publish the NPM packages.

To build, we need to follow below steps:

1. Open the terminal and use these commands

mkdir my-node-package
cd my-node-package

2. Now initialize a Node.js project and follow the instructions

npm init
//This will prompt you to enter the following information.
package name: (my-node-package)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)

After you provide the above information, a new file package.json will be created in your package directory.

3. Now create a file named index.js. This file is the entry point for your package, the same you mentioned in the above point while initializing your project. Define a function as a property of the exports object. Enter the following lines in your index.js and save your changes.

//This function will print the current date
exports.printDate = function() {
console.log("Current Date is", new Date());
}

Above, you have created your NPM package, which will print the current date. Now you need to create an account on npmjs.comOpen the terminal again and switch to your package directory.

//Run the following command to log into your npm account
npm login

After login, you need to run the following command in your project directory.

//This below command will publish your package to npmjs.com and your package will be listed in a few minutes on npmjs.com.
npm publish --access public

Make sure you will choose a unique name for your package; otherwise, you will get an error while publishing your package.

If you have noticed, we have used “— access public” in our command. This will publish the package as a public scope. You can also publish with a private scope, but that service is paid. For any organization, you need to have paid service if you want to keep your packages as private scope.

Let's install your newly published package and use it. Create a new Node.js project and run the following command.

npm install my-node-package --save

In your app.js or index.js for your new project use your package as follows:

const mypkgdate = require('my-node-package');
mypkgdate.printDate();
//Run the code:
node app.js
//You will get following output in console:
Current Date is 2019-10-17T07:48:46.728Z

You are now ready to create your own NPM packages. You can modify your packages according to your business requirements and publish the same.

 Ashwani Sharma

Ashwani Sharma