How to publish your own npm package?

By Prajwal Haniya

Tech-letter #9 | February 7, 2023

How to publish your own npm package?

Publishing a package may seem difficult, but believe me, it’s as easy as uploading a file to GitHub. Even I wasn’t aware of it until I published one. It’s very simple and in this letter, I will show you how to publish your own package to the npm repository.

  1. Create your own Repository on GitHub. Here I create a repository called tutorial-for-package-publishing. Once the repository is created make sure to create a folder in your local system preferably with the same name to avoid confusion. Then enter the following commands in your terminal:

    // create a readme file
    echo "# tutorial-for-package-publishing" >> README.md
    git init
    git add README.md
    git commit -m "first commit"
    git branch -M main
    
    //add the origin of your repo
    git remote add origin REPO LINK 
    git push -u origin main
    
  2. Add the index.js file to the folder that you have just created and linked with your GitHub.

  3. Go to the terminal and type npm init (make sure the path is inside the folder)

1

2

  1. Once you enter all the details, you will successfully create a package.json file inside your folder.

  2. Now, in the index.js file I will create a simple function that will return a string;

    function isThisTutorial() {
        return "Yes! This is a simple package publishing tutorial";
    }
    
    module.exports = isThisTutorial;
    
  3. Now you are ready to publish your package to the npm repository. Make sure to have your own npm account before you publish. And then type in the following commands in your terminal (take care of your path in the terminal)

    1. npm login
    /* 
    Enter the username, password & email. There will be a
    two-factor authentication. 
    */
    2. npm publish
    

    Then go to npm repo & search your package

    3.png

    You have successfully published your package!!