How to create and publish a new NPM package?

Tutorial on publishing a math module to npm in four steps

Velu S Gautam1 min readTechnology

Creating a new package and publishing it to npm is easy. Just follow the steps below.

Step 1 : Create a new npm account

Create an npm account using this Sign Up link. Once it's created, remember your username and password since you'll need them to log in from the console.

npm account creation page
npm account creation page

Go to your console and type

BASH
npm login
npm login from console
npm login from console

You'll be asked for your username, password, and email. Once you fill these in, you'll be logged into npm from the console.

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

Create the project you want to publish as an npm package 📦. Go to the project folder and run the command below, filling in the details as prompted.

For name, use something unique, e.g. npm-test-package.

BASH
npm init -y
npm initialization for a new project
npm initialization for a new project

Once npm init finishes, a package.json file is created in your folder. Check its properties and adjust anything you need to.

Step 3: Create an index.js file

The main property in package.json points to index.js. This is the file that runs by default when the package is used.

Here, index.js exports three math functions: sum, square, and cube. The whole file is just these lines:

JAVASCRIPT
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 this way. Whatever you attach to module.exports becomes importable in projects that install this package.

Step 4 : Publish our package to npm

First, give your project a unique name that doesn't already exist in the public npm registry, by updating the name property in package.json. Then run npm publish to publish your package.

BASH
npm publish

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

That's it. Your package is published to the npm registry, and you can see it in your npm dashboard.

Hurray!! You're now the owner of a public npm package. 😀

Comments