DEV Community

Cover image for Creating a NPM CLI application
Kuldeep Singh
Kuldeep Singh

Posted on

Creating a NPM CLI application

I am writing this blog post today, following a long day, based on my writing mood. You will discover today how to build a npm CLI application.

I'm thinking of developing a cli package that uses npm to make a choice for you. Making decisions is something I struggle with in my personal life. So i am going to make a CLI tool to let JavaScript make decision from me. while writing this blog post i am learning think myself.

I have created my first npm CLI application, and you can check it out. Just run npx make-me-a-choice in your terminal.

Requirement

  • Must know what is NPM and how to use it little bit.
  • You need to have basic knowledge of JavaScript & Node.js.
  • Have a working computer that is able to run Node.js.
  • internet connection is must.

Creating project

  1. Create a empty folder and give it the name according to project for me it is to make-me-a-choice.
  2. Now open project folder in terminal & run npm init fill all the details.
  3. Edit your package.json file add "bin" option like below.
{
...
"bin":{
    "<yourcommandname>":"bin/index.js" // use own command instead 
},
...
}
Enter fullscreen mode Exit fullscreen mode
  1. Create a file in bin\index.js it is going to be your & put below code in it or modify it according to your need.
#! /usr/bin/env node
console.log("Hellow from my NPM Package")
Enter fullscreen mode Exit fullscreen mode

That's it now just run npm i & npx <yourcommandname> for my case i have create a project. make-me-a-choice. So i have make-me-a-choice as <yourcommandname>.

You have successful create a package add to you Github repo and make it public to for other to see.

Publishing on NPM

Now to publish you package to npm you need to have account on npm, if not just create one email and password. Open your project directory in terminal and run npm adduser this will SignIn in to you account in npm. Then just run npm publish in terminal in you project.

Hurray You have successfully published your first package to npm🎉

Now just run npx <yourcommandname> or npx <yourprojectname> <yourcommandname>

If you get error because their is already a package with same as you project name. Use npm init --scope=@my-username & npm publish --access public.

Checkout out my repo as example for taking some inputs and doing think in cli: https://github.com/kuldeepdev407/make-me-a-choice

1 more think if you delete an npm package you can republish same package in after 24 hour only.

References

NPM docs:- https://docs.npmjs.com/creating-node-js-modules

Top comments (0)