How to publish an npm tool to ‘npm’

Athar Naveed
3 min readDec 25, 2023

--

Before starting let me tell you what npm is?
‘npm’ stands for “Node Package Manager”, what it is?
It allows you to publish and download packages from its site, ‘npm’. Downloading packages from npm is simple so, I am not going to explain it. let’s get back to our topic.

The prerequisites are:
1. You should have a TypeScript/JavaScript project. (I have a TypeScript project)
2. You should have a npm account

I have a simple calculator project, which is structured like this:

Folder structure

Since we have to make it a ‘npx’ (Node Package Execute: You can run JavaScript packages directly in cmd/shell without installing them) tool, we have to write this:

#! /usr/bin/env node

line of code at the top of our index.ts file. So your final code should look like this:

index.ts file

Next what you have to do is, run the “build” command which won’t be available by default so, you have to write it inside your custom scripts, inside the package.json file, also add the “bin” key and provide it with your project name and main “Javascript file (index.js in my case)”, like this:

package.json

After that, come to the terminal, and write the command to run the build:

npm run build

This will build your project.
If you want to test your code, like how it’ll work as a tool, in other’s computer? simply run:

npx your_project_name

It’ll run the project, if it won’t then it means there are some problems with your project.

Now we have to login to npm first, its pretty simple, just type this command in your terminal:

npm login

and it’ll take you throughout the login procedure.
As soon as it gets completed just write this command:

npm publish

and voila! your package is published on npm.

To use your package as a module, means some contributor wants to add some features in your module or use some methods of your code in his own so, he’ll use your npm package like this:

npm install <package_name>

But, if he or you wants to use it as a tool, means run it directly inside your shell/cmd/terminal so, you have to write this command:

npx <package_name>

It’ll get executed, like this:

how to write package name in shell/terminal/cmd
My simple calculator getting executed

And after getting your brain fried, my blog ends here.

If you want to use my simple not scientific 😊 calculator, you can use this command:

npx simp_calculator

or you can use simp_calculator here.

--

--

Athar Naveed
Athar Naveed

Written by Athar Naveed

Carving a path for junior devs so that they can easily navigate through the hurdles that made my learning experience challenging. Also loves Gardening!

No responses yet