How to create our own npm package and publish it?
Introduction
In this blog, we will see how to create our own custom npm package and publish it in the npmjs.com website
What is npm ?
Npm stands for 'Node Package Manager'. It is an open-source package manager for Node and JavaScript packages. It allows developers to find, build and manage code packages. It helps with workflow changes and makes development more manageable.
Let's get started!..
Package Overview
In this blog, we will be creating a sample package why-not-me
. This why-not-me
package takes two names as a input and randomly chooses one name, and generates a sassy message.
How to create a npm package?
Step 1 - Create a repository
Create a git repository with the same name as the package name. In this case, the repository name will be 'why-not-me
'.
Step 2 - Clone the repo
Clone the repository in your local machine using the git command git clone <repo link>
Step 3 - Initialize npm
Open the terminal inside the git clone folder, use the npm init
command to initialize npm. Provide answers to the prompted questions, like those below.
Step 4 - Create and edit index.js
Create an index.js file inside the why-not-me
folder and paste the content inside it.
function whyNotMe(option1, option2) {
const chosen = Math.random() > 0.5 ? option1 : option2;
// Choose random name
const rejected = chosen === option1 ? option2 : option1;
// Choosing random rejected name
return `Going with ${chosen}. Who needs ${rejected} anyway? `;
// Returns a sassy text
}
module.exports = whyNotMe; // Export the function
Step 5 - Login through npm
Use npm login
command to login to npmjs.com before publishing the package. Provide username, password and double verification code to verify the user.
Step 6 - Publish the npm package
Use npm publish
command to publish the Node package.
Note:
The name of the package should be unique, and no other package should have the chosen name.
Conclusion
Hurray ๐ฅณ๐. We successfully created our own npm package.
Resources:
Subscribe to my newsletter
Read articles from Roopa directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Roopa
Roopa
I'm a pre-final year computer science student at SRM with a strong academic background and technical skills. I am actively contributing to the beginner-friendly open-source repositories to showcase my skills in web development. I love to share my knowledge of technical skills and am a pro at debugging errors.