You wrote a helpful function and want others to install it with npm install. What do you actually need to do?
Quick answer: Create a
package.json, make sure the name is free, runnpm login, thennpm publish. I did this for my mock data package Koalaz, and it's much simpler than it looks.
Step 1: Create the package
mkdir my-cool-package
cd my-cool-package
npm init -yThen write your code in index.js:
export function shout(text) {
return text.toUpperCase() + "!";
}Step 2: Set up package.json
These are the fields that matter:
{
"name": "my-cool-package",
"version": "1.0.0",
"description": "Shouts your text",
"type": "module",
"main": "index.js",
"exports": "./index.js",
"files": ["index.js"],
"keywords": ["shout", "text"],
"license": "MIT"
}namemust be unique on npm. Check it atnpmjs.com/package/your-name.filesis a whitelist of what gets published. Without it, you may ship things you didn't intend (tests,.envfiles...).exportsdefines what users can import.
Want a scoped name (@you/package)? It works the same, but you must publish with --access public.
Step 3: Add a README
npm displays your README.md on the package page. Include:
- One sentence about what it does
- The install command
- A tiny usage example
A package with no README gets ignored.
Step 4: Test it before publishing
Never publish blind. See exactly what will be uploaded:
npm pack --dry-runEven better, install it locally in another project:
npm pack
# in another project
npm install ../my-cool-package/my-cool-package-1.0.0.tgzStep 5: Publish
Create an account on npmjs.com (2FA is required), then:
npm login
npm publishDone. Anyone can now run npm install my-cool-package.
Step 6: Publish updates
npm won't let you publish the same version twice. Bump it first with semantic versioning:
npm version patch # 1.0.0 → 1.0.1 (bug fix)
npm version minor # 1.0.1 → 1.1.0 (new feature)
npm version major # 1.1.0 → 2.0.0 (breaking change)
npm publishCommon mistakes
- ❌ Forgetting
filesand publishing secrets or huge folders - ❌ Publishing a name that's taken (you'll get a 403 error)
- ❌ Breaking changes in a
patchrelease - ❌ Not testing the packed
.tgzfirst - ❌ Losing 2FA recovery codes
Remember: unpublishing is heavily restricted, so double-check before you hit enter.