Table of contents
1.
Introduction
2.
Creating the npm package
3.
Creating or logging in to an npm registry account
4.
Publish your npm package to the npm registry
5.
Package Versioning
6.
Testing package installation
7.
FAQs
8.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Creating and Publishing your First npm Package

Author Dhruv Sharma
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

This article will take you through all the series of steps involved for an npm package to get published and become a part of the official npm repository for everyone to use. These are majorly the following steps:

  1. Create the npm package locally.
  2. If you don't have it already, create an NPM registry account; otherwise, login to your existing account.
  3. Publish your npm package to the npm registry.
  4. We are managing package versioning.
  5. You are testing your published package using npm install.

Creating the npm package

Since the article demonstrates and covers the steps that One should take to get an npm package published in the official npm registry, we will keep the package basic and straightforward so that we can focus on publishing the package. All packages' creating and publishing cycles are nearly the same; therefore, once one understands how it's done for something as simple as what we will be building in this article, you are good to go to publish your package.

Hence, we’ll create a simple package for generating random numbers using our module.

Prerequisite

All one needs to create(and then publish) an NPM package is the NPM command-line tool that goes by the name npm, i.e. 'Node Package Manager. It is distributed inherently with NodeJS, i.e. when one installs NodeJS, they automatically get npm installed. Visit here to download NodeJS.

To verify whether one installed npm properly, one can run. 

npm --version

It should output the version of npm that you installed.

Now create the package directory using the CLI and do the following:

# make the project directory
mkdir random-number-generator 
# cd into the directory
cd random-number-generator     
# Initialise the new NPM package in the project directory
npm init

The npm init command should lead one to the interactive session in the CLI that will be required to be answered on some questions, which are basically about the NPM package that one is creating. The command-line tool auto-suggests reasonable answers to most questions; if one feels the suggested answer not being good enough, one can skip the question by hitting enter. If you also don't have an answer to any of the questions, hit enter and continue; you can always edit it later.

After answering the questions, one will create a package.json file in the root of the project directory; the content will be similar to this:


{
  "name": "random-number-generator",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
You can also try this code with Online Javascript Compiler
Run Code

The Package.json file is the single and most important file as far as creating/publishing NPM packages is concerned; without it, one won't be able to publish their packages to the NPM registry.

Note that the main field in the package.json file refers to the file's name that would be loaded when another application requires the package; by default, it points to 'index.js'.

Creating the package that one would publish

The project that we are creating here is a simple one; all entry points to the utilities of any project, in most cases, would be composed in a single file. One can also create something more complex here.

For this package, create an index.js file in the root of the project directory and add the function for the random number generator:

function randomNumGenerator(min, max) {
  if(typeof(max) !== 'number' && typeof(min) !== 'number') {
    min = 0;  max = 1;
  }
 return (Math.random() * (max-min)) + min;
}
module.exports = randomNumGenerator;
You can also try this code with Online Javascript Compiler
Run Code

Notice that the module. Exports at the bottom of the file; whatever you are exporting here is what would be available for importing when others install the package.

Creating or logging in to an npm registry account

Authenticate

Before publishing their packages to the official npm registry/repository, one needs to have an existing npm registry account. If you don't have one already (since this is your first package, you wouldn't), you can do this here.

To set up an account, click here.

  1. Click on the Sign-Up button.


 

2. Choose and enter a username, email address and password. 

Note: The username must be unique. Be sure to keep track of your credentials; you will need them to publish. You will also receive an email to confirm your account.

If you have trouble creating an account, you can follow the documentation here.

After creating an account, go back to the command line and authenticate yourself with the command npm login, 

npm login

You would be prompted to provide your details, provide the required information and hit enter.

To test that the login was successful, enter the command npm whoami; one should log your username to the CLI.

Publish your npm package to the npm registry

Publish

Make final edits to your package.json before publishing. 

Note: Remember that the package's name should be unique in the NPM registry. Change it if necessary. You can check that here.

You add the previously skipped details, such as your npm registries, such as the keywords and author information.

{
  "name": "random-number-generator",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": ["random","number","generator"],
  "author": "your_registered_username <your_registered_email>",
  "license": "ISC"
}
You can also try this code with Online Javascript Compiler
Run Code

Now you can publish your package using,

npm publish

On publishing, one should see the following notices in the Terminal and get a confirmation email to check if one successfully published the package.

npm notice 
npm notice package: random-number-generator@1.0.0
npm notice === Tarball Contents ===
npm notice 304B index.js    
npm notice 289B package.json
npm notice === Tarball Details ===
npm notice name:          random-number-generator
npm notice version:       1.0.0
npm notice package size:  your_package_packed_size B
npm notice unpacked size: your_package_unpacked_size B
npm notice shasum:     77f1d53e8cb9f07318874706329c9e1c375f40fc
npm notice integrity:     sha512-VdzLzFcZVBgk+[...]rN7L2nfpRxr/w==
npm notice total files:   2
npm notice
+ random-number-generator@1.0.0

Package Versioning

The version value of the package here is a combination of 3 parts separated by a dot operator. Let's say the version is x.y.z

  1. Here, the first value (x in x.y.z) specifies the prior version of the package — Which means this version has Major code changes and it might contain breaking API changes.
  2. While the second value (y in x.y.z) specifies the minor version, which contains minor changes but will not contain breaking API changes.
  3. The third value (z in x.y.z) specifies the patch version, usually containing bug fixes.

In our case, you just added a readme.MD file is not an API change, so you can increment the patch version, which is the last part, by 1.

So change the version inside the package.json file from 1.0.0 to 1.0.1 and run the npm publish command again.

Testing package installation

To test the package, you need to install and use it. You can do the following to test the random-number-generator package:

# Create a test directory
mkdir random-number-generator-test 
# Change into the directory
cd random-number-generator-test
# Install the package     
npm install random-number-generator --save
# Create a test file
touch test.js

Use the module by importing it into your test file or directly copy this simple test snippet and paste it into the test.js file.

const randomNumberGenerator = require('random-number-generator');
console.log(randomNumberGenerator(1, 100));
You can also try this code with Online Javascript Compiler
Run Code

Now run the above snippet in the test.js file using node ./test.js; you should be able to see a random number logged to the console.

FAQs

1. What is the sequence of steps that one needs to follow to publish their npm package to the official npm registry?

To publish your npm package, one can take the following steps:

  • Create and test your npm package locally.
  • If you don't have it already, create an NPM registry account; otherwise, log in to your existing account.
  • Now, publish your npm package to the npm registry.
  • Test your published package using npm install.

2. What do the different parts in a package version denote?

The version value of the package here is a combination of 3 parts separated by a dot operator. The first value denotes the preliminary version of the package; the second value specifies the minor version change. In contrast, the third value indicates the patch version or minor bug fixes in the package.

Key Takeaways

In this article, we took a deep dive into the steps required to create and publish a simple NPM package so that anyone can install and use it. Once you have published the package, you can refactor the code or add functionality. If you do this, change the version number in the package.json before Publishing.

Recommended Readings:

NPX vs NPM

If you are preparing yourself for top tech companies, don't worry. Coding Ninjas has got your back. Visit this link for a well-defined and structured material that will help you provide access to knowledge in every domain.

Happy Learning!!!

Live masterclass