How to publish the first package on NPM

Tram Ho

Below, a small guide to publishing your own packages on npm.

You have written some code that you think is really useful! Now you want to publish it on npm so others can use your great package!

There are many configurations for npm but this article will only cover the essentials for your packages to be published into npm.

npm is included with Node.js. To check if npm is installed on your system, run this command on your terminal: npm -v

Create folder

Initialize npm

We will initialize npm with the command

Running npm init will ask you a few setup questions (for example, your package name, your package description, etc.).

You can press Enter Enter Enter for each question and this default summary for package.json will be created in your directory:

What is Package.json?

You see package.json as a recipe for your favorite food

Package.json contains all the metadata that describes the project (for example, potato pie) and all the dependencies needed to run it (ingredients: potato, flour, sugar, etc.).

Using all of this information, npm brings everything together so that your package can be easily downloaded and run by others.

Feel free to edit package.json to include a description and author information.

The only required fields in package.json are "name", version, "version" and "main". The "scrpit" has been deleted because we don't have any tests written.

Create the index.js file and add the following

Remember to export your code the same way you do for local files in your project.

Create a README

Generally, README is often used for the purpose of letting others know how to use your package.

Please create the README file in your root directory:

And finally Publish

Currently, the package looks like this:

Basically, this is the basic structure of the npm package.

Now we can publish it!

You will need an account on the npm registration website and if you have not logged in to it from CLI, you will be asked to login. You must also use the package name already in use

The end

Finally, a summary of the 3 steps to publish a package is as follows

  • Initialization: npm init
  • Add the code: index.js and create README
  • Publish: npm publish

Now if you want to use that package, run:

It will run and install the necessary dependencies.


Share the news now

Source : Viblo