How to publish an npm tool to ‘npm’
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:
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:
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:
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:
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.