Deep PatelNavigate back to the homepage

Create/ Publish your first NPM package

Deep Patel
June 14th, 2020 · 1 min read

1. Create a dir/folder to contain your packages code.

1bash mkdir firstnpmpackage

2. change path to dir/folder you just created.

1cd firstnpmpackage

3. Now run ..

1npm init

or simply(if you use this command instead npm will not ask you for the details of package and will generate it with defaults)

1npm init -y

and fill the required details.

Alt Text

4. Now create an index.js file in this folder, your folder should look like this

firstnpmpackage

  • index.js
  • package.json

5. write some code in index.js

1#!/usr/bin/env node
2 function randomNoGenerator(min, max)
3 {
4 if(typeof(max) !== 'number' && typeof(min) !== 'number')
5 { min = 0; max = 1; } console.log(Math.random() * (max-min)) + min;
6 }
7randomNoGenerator(5,10);

6. Now let’s modify our package.json a bit to make it work using cli.

1"bin":{ "demoproject" : "index.js" },

just add this thing in your package.json demoproject is the command you will use to execute your package through cli. index.js is the file that will be first triggered.


7. We are all ready to go , but wait wait you will really want to test your package locally before publishing it. Let’s do it first : run

1sudo npm install -g ./

Our package is installed in our local machine now, Let run it type this in your cli and see the result.

1demoproject

Alt Text


8. So, now we are done with testing .. Let’s publish it now , To make it published you first need to signup on npmjs.com once you are done signing up! Run :

1npm adduser

Give your login credentials..

9. Now we are ready to go .. open terminal in your root directory.. and Run :

1npm publish

Done…

NOTE : if it gives any error goto package.json and change name of your project any package with same name might be published before…
Github: Deep1144

More articles from Deep Patel

How to Add Sentry to your Angular project with Graphql

How to Add Sentry to your Angular project with Graphql

February 6th, 2022 · 1 min read

What is the !! (not not) operator in JavaScript?

What is the !! (not not) operator in JavaScript?

August 1st, 2021 · 1 min read
© 2020–2022 Deep Patel
Link to $https://twitter.com/pateldeep_ethLink to $https://github.com/deep1144Link to $https://www.instagram.com/deep__1144/Link to $https://www.linkedin.com/in/patel-deep-dev/Link to $https://dribbble.com/Deep1144