How I published my first and own package on NPM

npm logo

Every web developer has dealt with npm throughout their career. It is a fascinating packaging tool which provides you many important packages and helps you to add and manage your dependencies for your webapp.

What is NPM ?

But, have you thought that how this packages are available on npm? They are uploaded by such devs as you and me!

In this article I’m gonna tell you how to publish your own package on npm. This is a beginner level article and anyone with the basic web-development knowledge can do this by themselves.

Prerequisites

node -v

npm -v

Version output of both npm and node

How can you do it ?

  1. To start with, you need to create a account on npm’s official website npmjs.com
  2. Then you need to create a repo which you want to publish. Generally, this repo contains following files: index.js, package.json and a README.md file.

mkdir hello-world && cd hello-world

You can create your package.json with:

npm init

or just:

npm init -y

Your package.json will look like this

Note: We will be publishing our repo publicly so, there are possibilities that the repo name you’re publishing is already published. In this case, npm will not allow to publish your package. So, to overcome this problem, you’re suggested to keep your package-name unique or you should use your username (of npm account) with package-name.

i.e. @your-username/hello-world.

Now create a README.md file (you can create it manually or if you’re creating repo on github/gitlab then it’ll do that for you) and add description about your package. If you do not know about a markdown file or don’t know how to write in it you can take help from here: Mastering Markdown · GitHub Guides

3. Now, you can put your code in index.js (remember than the code you put in this file should be exported using module.exports or exports.your_function-name so that it can be used after importing in any repo).

If you do not have any code or repo written already, you can start with a classic hello-world as shown below (in index.js):

index.js

exports.helloWorld = function () {

console.log(“Hello there, I have been called from your module!”)

}

Now that we’ve all the files we need, it’s time to publish it!

4. Open your terminal or git bash (if on windows) and follow below steps:

npm login

it will ask for your username and password.

npm login

Now, you’re logged in your account so we can publish it.

npm publish — access public

Remember that you must use above command where your package.json is located.

Output of npm publish command

That’s it. Congratulations, you have just published your 1st package!

You can checkout your package on npmjs.com.

Module on npmjs.com

Here, I’ve also provided the link to my 1st repo https://www.npmjs.com/package/@utsavgadhiya/crypto-module.

Resources for more help:

Thank you for reading it. Have a great day!

Enthuastic Developer. Linux, Network and Security Excites me