Node Publish Packages

How to Publish Your Own NPM Package

One of the greatest features of Node.js is its open-source community. If you write a piece of code that you think other developers could benefit from, you can publish it to the NPM registry for the whole world to download!

In this tutorial, you will learn the step-by-step process of taking a local module and publishing it to npmjs.com.


1. Prepare Your Package

Before you publish, you need to ensure your package is ready for the public.

  1. Write the Code: Make sure your index.js file properly exports your functionality using module.exports or export.
  2. Check package.json: Your package.json must have a unique "name". If someone else on NPM has already used the name, you cannot publish it. It must also have a "version" (usually starting at "1.0.0").
  3. Add a README.md: Developers need to know how to use your code. Create a README.md file in the root directory explaining what your package does and providing code examples.

package.json

{
  "name": "my-super-unique-math-package-123",
  "version": "1.0.0",
  "description": "A package that adds two numbers together",
  "main": "index.js",
  "author": "Your Name",
  "license": "MIT"
}

2. Create an NPM Account

You cannot publish anonymously. If you don't already have one, go to npmjs.com and click "Sign Up" to create a free account. Remember your username, password, and email.

3. Login via the Terminal

Once your account is created, open your terminal, navigate to your project folder, and log in to NPM directly from the CLI:

npm login

You will be prompted to enter your username, password, and email. (Note: when typing your password, characters will not appear on the screen for security purposes).


4. Publish to the Registry!

Once you are logged in and inside the directory containing your package.json, executing the publish command is remarkably simple:

npm publish

If everything is correct (and your package name was unique), NPM will upload your code. Congratulations! Anyone in the world can now run npm install my-super-unique-math-package-123!


5. Updating Your Published Package

If you make changes to your code and try to run npm publish again, it will fail. NPM strictly enforces that you cannot overwrite an existing version.

To publish an update, you must increment the "version" number in your package.json. You can do this manually, or use an NPM command that automatically bumps the number for you:

# Bumps version from 1.0.0 to 1.0.1
npm version patch

Bumps version from 1.0.1 to 1.1.0

npm version minor

After bumping the version, run npm publish again!


Exercise

?

Why might an npm publish command fail for a brand new package?