How to build an NPM package?

How to build an NPM package?

The process of building an NPM package made easy

Β·

4 min read

Table of contents

When we hear about building a npm package we tend to assume it is something very complicated and it is meant to be built by only senior engineers.

But it's not how it looks like. An NPM package is just a reusable code to be used in multiple projects. So you abstract it and convert it to a generic code to be easily used in any project and then host it on NPM to be downloaded & used by anyone.

For eg. We use Express.js to create a server in Node.js which prevents us from creating an HTTP server from scratch as it is done by Express.js.

Now we understand what NPM packages are, let's move to build one ourselves.

We will build a digital dice 🎲 package. It will have a single-method roll() that will return a number between 1 to 6.

The first step when creating an NPM package is finding a name for the package such that there isn't any package with that name. Go to npm.js and check if your chosen package name has already been taken or not. I have chosen digital-dice as my package name you can just modify the name eg. digital-dice1, digital-dice-one, etc.

  • Create a folder digital-dice

      mkdir digital dice
      cd digital-dice
      npm init
    
  • Project files structure

    πŸ“‚ digital-dice

    |

    +β€” index.js

    |

    +β€” README.md

    |

    +β€” package.json

  • Update your package.json

      {
        // The name of your project or module.
        "name": "digital-dice",
    
        // The version number of your project. Follows semantic versioning (major.minor.patch).
        "version": "1.0.0",
    
        // A short description of your project, providing an overview of its purpose or functionality.
        "description": "This is a digital dice",
    
        // Specifies the entry point of your application, the main file that will be executed.
        "main": "index.js",
    
        // Defines npm scripts that can be run using the `npm run` command.
        "scripts": {
          // The "test" script is a placeholder for running tests,
          // currently just echoing an error message and exiting.
          "test": "echo \"Error: no test specified\" && exit 1"
        },
    
        // An array of keywords that describe your project.
        "keywords": [
          // Keywords to help others discover this package.
          "digital-dice",
          "dice"
        ],
    
        // Specifies the author of the project.
        "author": "Finson Coutinho",
    
        // Specifies the license under which your project is distributed. ISC is a permissive open-source license.
        "license": "ISC"
      }
    
  • Write package code in index.js

      // Define a function called 'roll' that generates a random number between 1 and 6
      const roll = () => {
        // Generate a random decimal between 0 (inclusive) and 1 (exclusive)
        const rn = Math.random()
    
        // Scale the random decimal to the range 1 to 6
        // Multiply by 6 to get a range between 0 and 5, then add 1 to shift the range to 1 to 6
        const randomNumber = Math.floor(rn * 6) + 1
    
        // Return the generated random number
        return randomNumber
      }
    
      // Export the 'roll' function to make it accessible to other modules
      module.exports = { roll }
    
  • Write README.md

      # Digital Dice
    
      This package provides you with a digital dice.
    
      ## Features
    
      - **Roll**: you can roll a dice inorder to get an output between 1 to 6.
    
      ## Installation
    
      To install the package, use npm:
    
      ```bash
      npm i digital-dice
      ```
    
      ## Usage
    
      ```js
      import { roll } from 'digital-dice'
    
      const output = roll()
    
      console.log(output)
      ```
    
  • Publish to npm:

    1) If you don't have an npm account, create one by going to npm.js

    2) Log in to your terminal with your npm account by running:

      npm login
    

    You will be redirected to a webpage where you have to enter the OTP received on your registered email ID

    3) Finally, publish your package by running:

      npm publish
    

Usage

npm i digital-dice
  • import roll() from β€˜digital dice’ and execute the node app
import { roll } from 'digital-dice'

const output = roll()

console.log(output)

Congratulations πŸŽ‰, you have just built, published and used your own NPM package.

If you found this blog helpful then do check my YouTube channel and Twitter where I post content related to full-stack development.

Thank you πŸ‘‹βœ¨

Β