+91 9404 340 614    gyaanibuddy@gmail.com

Like
2 Likes

Make Your Own npm Package in 5 Mins - 2022

Last updated on Jan. 20, 2022, 4:37 a.m. by rugved

Tutorial on creating and publishing your own npm package quickly

Introduction

If you use Node.js you must be using npm packages all the time. They are so helpful and surprisingly it is very easy to make your own npm package and publish it on the internet where it is accessible to the world.

What are we going to build?

In this article, we will build a simple npm package that returns the current date and time. Later, we will publish it and install it in a different project.

Let's Code

  • Create a folder and run npm init.
mkdir get-the-date-and-time
cd get-the-date-and-time
npm init 
  • After running npm init it will ask you for basic details. When it asks you to enter your package name try to think of a unique name.

  • Create index.js in the directory where package.json is present. This will be the main file where you write all your functions. These functions can later be used by the users who install your package.

  • Add your functions in index.js in the following format
exports.functionName = () => {
    // function logic goes here
}
  • As we are building a package that returns date and time, here is the index.js file for the demo.
exports.getDateAndTime = () => {
    var today = new Date();
    var date = today.getDate() + "-" + (today.getMonth()+1) + "-" +     today.getFullYear();
    var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
    var dateTime = date + ' ' + time;
    return dateTime
}
  • Next, if you haven’t already created an account on the official npm website https://www.npmjs.com/.
  • In the terminal, type npm login and type in your username and password.

  • We are almost done. All that is left to do is publish our package. To do so enter the following in the terminal.
npm publish
  • Sometimes your package name might already be taken or it may be very similar to other packages. In that case, go to package.json and change the name property to something else and run npm publish again.

  • Your package is now available to everyone and you can check it out on your profile by logging in on https://www.npmjs.com/

Let's test if it really worked

  • Create a new project and repeat the earlier steps.
    1) Create a new directory
    2) npm init
    3) Create index.js
  • Now to install your package by running the following command.
npm install YOUR_PACKAGE_NAME

  • Now that your package is successfully installed you have access to all the functions you had written in it. To use the functions, we need to “require” the package in index.js. Here is the screenshot of the sample working with output.

Hurray! Next time you build any useful function, publish it so that others could install it too :)

...

by rugved
KJ Somaiya College of Engineering Mumbai

Avid learner
blog comments powered by Disqus