DEV Community

Cover image for How to publish packages to npm
Clément Gaudinière
Clément Gaudinière

Posted on

How to publish packages to npm

Hello everyone, have you ever created a project that should be accessible to all and quickly ? Fortunately, thanks to the npm package system, you can download any package in one command line. Today in this tutorial I'm going to show you how to publish your package to npm, so that it's available to everyone.

Prerequisites

The first thing you will need is to have Node.js installed on your machine. To do this, go to the official Node.js website, and download the latest version.

The second thing you will need is an npm account. If you don't have one, you can create one for free on this page: https://www.npmjs.com/signup. This step is essential as you can only publish packages if you are logged in. Once you have created your account, and validated your email address (required), memorize your username and password.

Once this is done, you are ready to go !

Publish to npm

Often, when we publish a package on npm, it is on a GitHub repository. In our example, we will imagine that the GitHub package is called: example-package, and is available at this address : https://github.com/user/exemple-package.

Go to your project folder, and open a command prompt. In this one, enter npm login.

npm login
Enter fullscreen mode Exit fullscreen mode

You then enter your npm username (that's why you had to remember it) and your password. Don't worry, if you don't see the number of characters in the password, it's perfectly normal (linuxians know).

Now you will have to create a file named package.json, to do this you can use the following command : npm init. It allows you to fill in all the necessary fields from the command prompt. Be careful though, the package name must be unique, so you may not be able to choose a package name that is already taken. Then enter the version or click on enter, then the description, etc. For the git repository, you enter the url of your repository, in my case, it is https://github.com/user/exemple-package.

npm init
Enter fullscreen mode Exit fullscreen mode

Once this step is complete, you can check your package.json file to see if everything is in order.

Now it's the big moment, you are ready to publish your package on the npm network with the magic command : npm publish.

npm publish
Enter fullscreen mode Exit fullscreen mode

Now you can test if your package is on the npm network, by going into an empty folder and running the command npm install [name] in my case, this gives: npm install example-package. If any files appear in your folder, it has worked. Packages are often found in a folder called node_modules.

I hope this tutorial has helped you publish your own package on the NPM network. If you have any questions, don't hesitate to ask them in the comments. See you next time for another tutorial. 👍

Top comments (0)