hectane logo

How to create and publish a new NPM package?

Tutorial on publishing a math module to npm in four steps

How to create and publish a new NPM package?

Creating a new package and publish in npm is very easy, just follow the below steps.

Step 1 : Create a new npm account

Create a new account in NPM using this Sign Up link. Once created remember the username and password of npm login (we require that for console login)

npm account creation page

Go to your console and type

npm login
npm login from console

You will be asked username, password and email id. Once filled you will be logged into NPM in console.

Step 2 : Create a project you want to publish in npm

Create a new project that you want to publish as an npm package 📦. So go the folder your project is and do below command and fill in necessary details as shown below. 

In the name: npm-test-package ( this should be a unique name.)

npm init -y
npm initialization for a new project

Once npm init is done a package.json file will be created in your folder. You can verify the properties and make changes if necessary. 

Step 3: Create an index.js file

This main property in package.json points to index.js. This means the default file to run when we run the npm package is index.js

Now I am creating 3 math functions sumsquare and cube in index.js. My whole index.js file has only below lines of code.

const sum = (x, y) => x + y; 
const square = x => x * x; 
const cube = x => x * x * x; 

module.exports = { sum, square, cube };

You can export any function. That module.exports can be imported in the project that use this npm package.

Step 4 : Publish our package to npm

First you need to give a unique name to your project that doest exist in npm public repository, for that you should update your package.json name property. Then do npm publish to publish your package.

npm publish

Then login to your npm https://www.npmjs.com/login

Done your package is published in npm repository. You can see that package in your npm dashboard. 

Hurray!! you are now a owner of a public NPM package. 😀