Publishing your own NPM package is a milestone every JavaScript developer should experience. Whether you’re sharing utilities with the world or building internal tools for your team, packaging your code through NPM makes it reusable, scalable, and organized.
NPM (Node Package Manager) is a public code library and package manager for JavaScript. It allows developers to use and share pre-built solutions (called packages) instead of reinventing the wheel.
Each package contains reusable code bundled with metadata (like version, author, and dependencies) in a file called package.json.
If you haven’t installed Node.js yet, head over to the official Node.js website and download it.
Once installed, open your terminal and check the versions:
node -v
npm -v
NPM is bundled with Node.js, so no need for a separate installation.
Make a folder for your new package:
mkdir my-awesome-package
cd my-awesome-package
Run the following command to create a package.json file:
npm init
You’ll be prompted to fill in details like:
Package name: Must be unique across NPM.
Version: Start with 1.0.0.
Entry point: The file that exports your logic (default: index.js).
License: Typically MIT or as per your preference.
At the end, it will generate a package.json file that looks something like this:
{
"name": "my-awesome-package",
"version": "1.0.0",
"main": "index.js",
"license": "MIT"
}
Create an index.js file with the logic you want to share. Here’s a simple example:
// index.js
function greet(name) {
return `Hello, ${name}!`;
}
module.exports = greet;
This small package exports a greet function that anyone can use after installing your package.
Step 5: Log In to NPM
If you don’t already have an NPM account, create one here.
Then, in your terminal, log in:
npm login
Enter your username, password, and email.
Step 6: Publish Your Package
Once you're ready to share your code with the world:
npm publish
⚠️ Your package name must be unique. If it's already taken, rename it in
package.json.
If everything goes well, you’ll get a success message, and your package will be live on npmjs.com.
To test it in a new project:
npm install my-awesome-package
Then use it:
const greet = require("my-awesome-package");
console.log(greet("Moly")); // Output: Hello, Moly!
✅ You’ve Published Your First NPM Package!
You’ve now successfully created, developed, and published your first NPM package. With this foundation, you can keep improving it, add TypeScript support, write tests, or even automate releases using tools like semantic-release.
Happy coding — and welcome to the open-source world! 🚀