The Wayback Machine - https://web.archive.org/web/20240917131654/https://www.geeksforgeeks.org/steps-to-create-and-publish-npm-packages/
Open In App

Steps to Create and Publish NPM packages

Last Updated : 02 Sep, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will learn how to develop and publish your own npm package (also called an NPM module). 

There are many benefits of NPM packages, some of them are listed below:

  • Reusable code
  • Managing code (using versioning)
  • Sharing code

The life-cycle of an npm package takes place like below:

module-lifecycle

Module Life-cycle

1. Setup a Project: Setting up a project is required before doing anything.

  • Install Node.js
  • Create an npm account.
npm-signup

npm-signup

  • Logging in to the npm account using npm login
npm-login

npm-login

2. Initializing a module: To initialize a module, Go to the terminal/command-line and type npm init and answer the prompts.

npm-init

npm-init

  • In the version prompt, set it to 0.0.0. It initializes the module. If you keep it 1.0.0, it means that the current module version is the first major release to the potential downloaders. Of course, you don’t want the first major release to be only a blank slate and full of bugs.
  • In the main prompt, choose the entry point of the module. Potential downloaders will use it as the entry point to the module. Note that the entry point is ‘src/index.js’ which is considered a standard practice these days to put your code in an ‘src’ directory.
  • In the test command prompt, simply press Enter. In the image above, it has been edited out because of some typo mistake. You can change your test command from the eventually forming package.json file as well.
  • In the git repository prompt, you can fill the URL of the git repository where the package will be hosted.
  • Fill in the keywords, author, and license or you can press ‘Enter’ your way through them. These can be later modified in the package.json.
  • Add “type”: “module” in the package.json file in order to use the latest import/export ES6 feature.
  • Include a README.md file in the project for potential downloaders to see. This will appear on the homepage of your module. Note that, the file should be a markdown. A README.md should be added to an npm module so that potential users for the purposes of serving them with information like module description, how to use the package, how to contribute to package, etc.

Ultimately, it is desirable if our project directory looks something like this:

project-directory-structure

project-directory-structure

3. Building a module: This phase is the coding phase. If you have any experience in using NPM modules, you would know that NPM modules expose methods that are then used by the project. A typical control flow is:

function-call-workflow-function-present-in-npm-module

Function-call-workflow-that-present-in-npm-module

Let’s first implement a simple function that adds two numbers in the npm module. This function looks like the below: 

File Name: index.js 

javascript




export const gfgFns = {
  add : function addTwoNums (num1, num2 ) {
    return (num1 + num2) ;
  }
}


Note that, the structure of the index.js file (which is the entry point of the npm module that we are building).

  • const gfgFns = {} The object that is exported for others to use.
  • add: function addTwoNums() The function name (addTwoNums) is marked by ‘add’. This ‘add’ name is used to call this function to add two numbers.
  • module.exports = gfgFns The gfgFns object is then exported with this name. When this function needs to be used in some other file.

4. Publishing a module: After completion of the coding module, publish the npm package. To publish the package, there is one thing to keep in mind- if your package name already exists in the npm registry, you won’t be able to publish your package. To check if your package name is usable or not, go to the command line and type

npm search packagename

If your package name is usable, it should show something like the image below.

npm-search-gfgnpmpkgupload-cmd-1

npm-search-gfgnpmpkgupload-cmd-1

If your module name already exists, go to the package.json file of the npm module project and change the module name to something else.

Now after checking the name availability, go to command-line/terminal and do the following:

npm publish
npm-publish-cmd

npm-publish-cmd

Now, let’s try to use this module and see if it works.

  • Make a fresh project directory.
  • In the terminal, type npm init to initialize the Node project.
  • Now do npm install gfgnpmpkgupload to download the npm module that we just made.
appjs-npmpkgupload-directory-add_function

appjs-npmpkgupload-directory-add_function

  • Now everything is set, let’s try to run the node.js file and see if our module is correctly uploaded, published, imported in our new project, and used.
node-appjs-add(4+5=9)-run-success-11

node-appjs-add(4+5=9)-run-success-11

5. Updating and managing versions: If a software is being developed, it is obvious that it has versions. Versions are a result of bug fixes, minor improvements, major improvements, and major releases. To cater to versioning, NPM provides us with the following functionality.

Versioning and publishing code: NPM allows us to version our module on the basis of semantic-versioning. There are three types of version bumps that we can do, ie, patch, minor, and major. For example, if the current module version is 0.4.5:

# note how minor version upgrade resets patch version to 0, similarly,
# major version upgrade sets minor and patch #to 0.
> npm version patch  # update version to 0.4.6
> npm version minor  # update version to 0.5.0
> npm version major  # update version to 1.0.0

When we run the above command, the version number in the package.json file is automatically updated as well. 

Note: If the module is being re-published without bumping up the version, the NPM command line will throw an error. For example, look at the below image.

npm publish abort due to unchanged version number

npm publish abort due to unchanged version number

Here, the command line threw an error because an ‘npm publish’ was attempted without bumping up the version. 
An obvious note: You can’t bump down the version. For example, the version can’t change from 0.1.2 to 0.1.1. 

What happens when the user has an older version of the module? When an npm module is re-published (updated), the users just have to run ‘npm install gfgnpmpkgupload’ (npm install <packagename>) again to get the latest version. 

A package dependent on other packages: In the journey of developing packages, it is common to search, use, and see dependencies. Doing this takes place like something below:

  • In the npm module project, install the dependencies that are required by your npm module.
  • Install those dependencies to your project using
npm install packagename1[ packagename2]
  • Check that these dependencies are now mentioned in the ‘dependencies’ key in the package.json file. Note that the dependencies and their version mentioned here will be carried on forward with the npm package.
  • After assuring that all the above steps are rightly executed, simply publish the module using
> npm version minor
npm publish
  • The above procedure should execute successfully, and the result should be available to see in the npm registry website like below:
three-dependencies-prompt-jest-mathsjs

three-dependencies-prompt-jest-mathsjs

Building a more complex module: Let’s try to build a module that reads a txt file, extracts numbers from the file, adds them all, and display the result in a console. To do this, our npm module should be this. 
Now, that we have our module set, let’s import it into our new project using

npm install gfgnpmpkgupload

Before running the above command, run

npm init -y

to set up the project. 
Make your project file structure like below:

npmpkguploadtest project structure

npmpkguploadtest project structure

The datafiles should contain a numFile.txt that has the numbers that have to be added and displayed in the console.

// numFile.txt - sum = 55
1 2 3 4 5 6 7 8 9 10

To consume this numFile.txt, we will have a gfgapp.js that will do the actual addition.

npmpkguploadtest-gfgappjs

npmpkguploadtest-gfgappjs

To test this, go to command-line and run

node gfgapp.js
node gfgappjs commandline view run success

node gfgappjs commandline view run success

NPM module boilerplate: NPM module boilerplates are also available for project scaffolding on yeoman.io . Various combinations of technologies are available and you can use the generator that you like. To start, go to Yeoman Generator Search and search for something like ‘npm module boilerplate’. 

Unpublishing an NPM package: An NPM package should be taken down within 72 hours of the initial publish. The other way is to contact the npm registry. If you are unpublishing within 72 hours, use the following command:

npm unpublish packageName

NPM’s unpublishing packages from the registry is a good page to go through to learn more about this. 

Example: Use the published package to add two numbers. 
Filename: app.js 

JavaScript




import GFGFns from 'gfgnpmpkgupload';
console.log(GFGFns.add(4, 5));


Output:

node-appjs-add459-run-success-1

node-appjs-add459-run-success-1



Similar Reads

How to Publish NPM Packages in the Package Registry ?
The npm Package Registry serves as an invaluable tool for publishing npm packages for individual developers or organizations. This article will guide you through the requirements, configuration, and usage of the npm package registry. Table of Content Setting Up the Package RegistryPublishing a PackageAuthenticating via the .npmrcPublishing a packag
5 min read
How to Get a List of Globally Installed NPM Packages in npm ?
Learning how to retrieve a list of globally installed NPM packages is essential for developers managing their Node.js environment. Utilizing npm, the Node Package Manager, enables users to efficiently manage packages across projects. This article will guide you through getting access to global NPM packages, which will further help you to enhance yo
2 min read
How to build and publish an NPM package for React using Typescript?
In development, creating and distributing reusable components is essential for building scalable and maintainable applications. With the popularity of TypeScript and React, you can easily package and share your components as NPM packages. This tutorial will teach us how to create and release our NPM packages (NPM modules). Prerequisites:GitHub Acco
4 min read
How to publish a ReactJS component to NPM ?
Follow these simple steps in order to publish your own ReactJS component to NPM. Step 1: Initial Setup In order to publish any ReactJS Component to npm (node package manager), first we have to create a React component in the React app. Following are the instructions for creating any react app. Create a React application using the following command:
3 min read
Introduction to packages and modules in npm
The Node Package Manager (npm) serves as a tool for the JavaScript programming language functioning both as a command line utility and package manager. It is the choice for managing dependencies and sharing packages within the NodeJS environment. The public npm registry acts as a centralized platform where developers can upload, discover, and incor
4 min read
How to list npm user-installed packages in Node.js?
What is Node.js? Node.js is an open source and cross-platform runtime environment for executing JavaScript code outside of a browser. Click here for more. What is npm? Here, "npm" stands for "Node Package Manager" which is the package manager for Node.js and serves as a command-line utility for interacting with the npm to install different online p
2 min read
How to document NPM packages ?
In this article, we will see how to write the documentation of an NPM package. Documentation is an essential part of any NPM package because it gives an idea about the package method and how to use them. Good documentation makes your npm package popular npm packages. The Documentation of the npm package depends on many factors, see the step-by-step
2 min read
Top npm packages for node
NodeJS has become an effective tool for server-side development, thanks to its extensive ecosystem of npm packages. These packages offer a wide range of functionalities, from web frameworks to utility libraries, enabling users to build robust and scalable applications efficiently. In this article, we'll delve into seven top npm packages for NodeJS
4 min read
8 Most used NPM packages for React
React, a popular JavaScript library for building UI (user interfaces), offers a vast ecosystem of packages to enhance development efficiency and functionality. React allows developers to utilize individual parts of their application on both the client side and the server side, which ultimately boosts the speed of the development process. Table of C
7 min read
What is the meaning of the "at" (@) prefix on npm packages ?
Users regularly come across package names prefixed with "@" and a string of characters in the extensive npm (Node Package Manager) ecosystem. Those who are not familiar with the meaning of this prefix may have some questions. This post will explain the definition and function of the "at" prefix in npm packages, as well as its history, application,
3 min read
How To Reinstall Packages With NPM ?
Reinstalling packages with npm is a common task in Node.js development when you need to refresh or update dependencies for your project. This process ensures that you have the latest versions of packages and resolves any issues related to package versions or corrupted installations. This article will cover the steps and techniques for reinstalling
3 min read
Top npm Packages for React
ReactJS, often referred to as React is a popular JavaScript library developed by Facebook for building user interfaces. It emphasizes a component-based architecture, where UIs are built using reusable components. It has a vast range of libraries which helps it to become more powerful. In this article, we’ll see about the top npm packages for React
4 min read
Where does NPM Install the packages ?
NPM is the default package manager for Node.js , and it is used to install, manage, and distribute JavaScript packages. When you add a package using NPM install, the location of the installed package depends upon whether the package is installed globally or locally. Table of Content Local Installation Global Installation Common Issues and Solutions
3 min read
Difference between npm i and npm ci in Node.js
The following difference covers how npm i and npm ci command are different from each other and their functioning. The npm which is called a node package manager which is used for managing modules needed for our application. npm i: The npm i (or npm install) is used to install all dependencies or devDependencies from a package.json file. Syntax: npm
2 min read
Difference between npm install and npm update in Node.js
NPM is like a powerhouse for Node.js that contains all the necessary modules for the smooth running of the node.js application. It gets installed on our machine when we install Node.js on our Windows, Linux or MAC OS. How to install Node on the machine? Refer to this article. NPM has 580096 registered packages. The average rate of growth of this nu
5 min read
How to solve npm error npm ERR! code ELIFECYCLE ?
In order to solve the "npm ERR! code ELIFECYCLE " error which is a very common type of error that occurs during npm operation on our command prompt or terminal such as installing npm or an npm package, follow the steps given below : Terminal output of the error : Follow below steps to fix the error : Step 1 : In our first step we will try cleaning
2 min read
Axios npm - How to Install Axios npm in Terminal?
Axios is a popular JavaScript library for making HTTP requests in web applications. It simplifies the process of sending asynchronous requests and handling responses. It is commonly used with Node.js and in browser-based projects and can be installed via NPM (Node Package Manager). In this article, we will explore the step-by-step process of instal
2 min read
npm cache clean - How to Clear the Cache in NPM ?
Clearing the cache in NPM (Node Package Manager) is very important. It helps to resolve various issues and ensures smooth functioning of the Node.js projects. The NPM cache stores downloaded packages and their metadata, which can sometimes become corrupted or outdated, leading to installation problems, dependency conflicts, or other issues. Table o
5 min read
Remove NPM - npm uninstall
To remove npm (Node Package Manager) from your macOS system, you can't use npm uninstall since npm itself doesn't support uninstalling itself. Instead, you need to remove it manually along with Node.js. Table of Content What is NPM?What is NPM remove?Installing a package using npmUninstalling a Package using npmRemove npmRemove a Dev DependencyWhat
2 min read
Create a New React App - npm create-react-app
The create react app command allows us to create a development environment and install all necessary libraries for creating single-page applications using React. The CRA tool is used to set up a new React project quickly, providing a standard structure and configuration. It includes a development server, build scripts, and support for modern JavaSc
3 min read
How to Create Your Own Android Library and Publish it in GitHub?
Android libraries are tools for developers, that offers reusable code components and functionalities to streamline app development. Creating and publishing your own Android library on GitHub allows you to share your code with the wider developer community, contribute to open-source projects, and establish your expertise. In this article, we'll walk
5 min read
How to Create and View Access Tokens in NPM ?
Access tokens are important components in the npm ecosystem, used as authentication mechanisms for users to interact with npm registries securely. They grant permissions for actions such as publishing packages, accessing private packages, or managing user accounts. In this article, we will see how to create and view access tokens in npm. What are A
2 min read
npm create react app
Creating a React application has never been easier thanks to Create React App, a tool developed by Facebook. It sets up a new React project with a sensible default configuration, allowing developers to focus on writing code without worrying about build configurations. This article will guide you through the steps to create a new React app using Cre
3 min read
How to Create an NPM Library from React Components ?
Creating an NPM library from React components involves configuring Babel and Webpack, bundling your components, and publishing them to NPM. This process enables easy reuse and sharing of React components. In this tutorial, we'll create a library containing a button component that changes color when clicked. Then we'll demonstrate how to consume thi
3 min read
How to create a REST API using json-server npm package ?
This article describes how to use the json-server package as a fully working REST API. What is json-server? json-server is an npm(Node Package Manager) module/package, used for creating a REST API effortlessly. Data is communicated in JSON(JavaScript Object Notation) format between client and server. Installation: Execute the below command in your
4 min read
How to Publish Your Front-End Over Surge Cloud Platform ?
Requirement: NPM must be installed As a front end developer, we create lots of cool designs and we want to showcase them to others. But as students, we may not want to buy domains in order to get the site live on web. There are some free tools available like github and Heroku but the setup is a little complicated when it comes to publishing the fro
2 min read
How to Publish Any API on Rapid API Platform ?
The Rapid API Platform is a multi-cloud, customized hub to find, connect to, and share APIs. The API Platform improves the developer experience with integrated tools for designing, testing, monitoring, building, publishing APIs, and more. If you have any Rest API endpoints already built, you can easily list your API on the Rapid API platform. In th
2 min read
Publish Websites on GitHub Pages with a Custom Domain
GitHub Pages is a free hosting service provided by GitHub that allows you to publish static websites directly from your GitHub repositories. By default, GitHub Pages provides a domain in the format - username.github.io/repository, but you can also use a custom domain for your website. This article will guide you through the process of publishing we
3 min read
How to Publish a Static Website on GitHub?
Publishing a static website on GitHub is a great way to share your work with the world. GitHub Pages is a service offered by GitHub that allows you to host your static websites directly from a GitHub repository. In this article, we’ll walk you through the steps to publish your static website on GitHub. Hosting a website enables many web users to ac
6 min read
How To Publish A New Branch In Git?
Git is a distributed version control system, offering powerful tools for collaboration, version tracking, and branching. One of its key features is branching, which allows developers to work on different features or fixes simultaneously without interfering with the main codebase. This article will guide you through the process of publishing a new b
4 min read