Publishing Your NPM Package
Creating shared utility libraries is key to keeping code DRY (Don't Repeat Yourself) across projects. Let us learn how to structure and publish a package to the npm registry.
1. Structuring the Package Directory
Create a clean, dedicated directory for your library. A basic npm package requires the following file layout:
my-utility-library/
├── src/
│ └── index.js
├── README.md
├── LICENSE
└── package.jsonIn src/index.js, write the helper functions that you want to share:
// src/index.js
export function capitalize(str) {
if (typeof str !== "string") return "";
return str.charAt(0).toUpperCase() + str.slice(1);
}
export function isNumber(val) {
return typeof val === "number" && !isNaN(val);
}2. Defining Entry Points in package.json
Before publishing, configure your package.json file so that importing projects can locate the index file:
{
"name": "my-custom-string-helpers",
"version": "1.0.0",
"type": "module",
"main": "src/index.js",
"files": [
"src",
"README.md"
],
"author": "Your Name",
"license": "MIT"
}- main: Defines the entry point of the package.
- files: Specifies which folders and files should be uploaded to the registry, keeping the package size light by ignoring logs or tests.
3. Registering and Authenticating with NPM
Before pushing code, create a free account at npmjs.com.
Once your account is set up, log in from your local terminal:
# Log in to NPM (opens browser auth or requests credentials)
npm loginVerify that you are logged in successfully:
# Check current authenticated user
npm whoami4. Publishing the Library
To upload your package to the public registry, run this command in your library directory:
# Publish a public package
npm publish --access public5. Version Upgrades (npm version)
When you make changes to your library, you must increment the version number in package.json before publishing again. You can use the version command to update the version and create a corresponding Git tag automatically:
# Increment patch version (e.g., 1.0.0 -> 1.0.1)
npm version patch
# Increment minor version (e.g., 1.0.1 -> 1.1.0)
npm version minor
# Publish the update
npm publish