Publishing your first npm package

A step-by-step guide on how to publish a npm package

Margarita Morozova
Level Up Coding

--

Build amazing things with npm

In this blog post, I will show you how easy it is to publish your own npm package in the world’s largest software registry. For this tutorial, I created a dummy file that we will publish together.

index.js

I created an index.js file. Nothing fancy here, it just prints “Hello World!”. To be able to publish our package with npm, we need to create a package.json file. To create the package.json run

npm init

Enter the name of your package. Since the name must be unique, make sure first that there is no package with the same name in the npm repository. I will add my initials to my package to make sure the name is unique. Version should be 1.0.0 since it’s a first release. Add a description to your package if you’d like. The entry point and git repository values can stay by default. Add the author’s name and the rest also can stay by default.

First, before we can publish our package, we have to receive credentials from npm. Go to https://www.npmjs.com/ and create a free account. Once you have the account, you can use your username and password to publish packages with npm.

Run in your terminal (make sure you are in the main directory of your package)

npm login

npm login will connect your credentials with the local npm so you could publish your package. Enter your username and password (you won’t see your password appearing on the screen while typing — just keep typing it and hit enter once done), enter your email that you used to create an account with npm.

Now run:

npm publish

That’s it! This command will publish your package to the npmjs.com registry.

Now let’s check that we successfully published our first package. Go to the https://www.npmjs.com/package/<name-of-your-package-here>. There you go! Congratulations, you’ve just published your first package!

Now this package can be installed on any machine with this command:

Now if I go back and delete my files from the folder and then run the above command, npm will download my package and install it under the node_modules directory.

If you followed my tutorial and published a dummy package to npm, make sure you remove it from the registry. Let’s be responsible developers and not create unnecessary mess.

Run

npm unpublish <name-of-your-package> -f

This command will unpublish the entire package (you only have 72 hours to remove it).

Hopefully this small guide was helpful to you. Can’t wait to see new cool npm packages out there! 

--

--