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.
Before you publish, you need to ensure your package is ready for the public.
index.js file properly exports your functionality using module.exports or export.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").README.md file in the root directory explaining what your package does and providing code examples.
{
"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"
}
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.
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).
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!
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 patchBumps version from 1.0.1 to 1.1.0
npm version minor
After bumping the version, run npm publish again!
Why might an npm publish command fail for a brand new package?