Publishing Your First Package to npm
This guide walks you through publishing a package to the npm registry from scratch.
Prerequisitesโ
- Node.js 18+ installed
- An npm account โ sign up at npmjs.com
Minimal package.jsonโ
Every publishable package needs a package.json. Create one with:
mkdir my-package && cd my-package
npm init -y
Edit it to include the essentials:
{
"name": "my-package",
"version": "1.0.0",
"description": "A short description of what this package does",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"files": ["dist"],
"keywords": ["example"],
"license": "MIT"
}
Key fieldsโ
| Field | Purpose |
|---|---|
name | Package name on the registry. Must be unique or scoped. |
version | Current version following semver. |
main | Entry point for CommonJS consumers. |
exports | Modern entry point map (Node.js 12+). |
files | Whitelist of files/directories to include in the tarball. |
types | TypeScript type declarations entry. |
Scoped Packagesโ
Scoped packages are namespaced under your org or username:
{
"name": "@my-org/my-package"
}
Aliz has an @aliz.ai organization on npm. Our packages should be published under the @aliz.ai scope (e.g., @aliz.ai/my-package).
By default, scoped packages are published as private. To publish publicly:
npm publish --access public
Controlling What Gets Publishedโ
files field over .npmignoreThe files field in package.json is a whitelist โ it's safer and more predictable than maintaining a .npmignore blacklist.
The files field specifies exactly which files and directories are included in the published tarball:
{
"files": ["dist", "README.md", "LICENSE"]
}
Some files are always included regardless: package.json, README, LICENSE, and CHANGELOG.
To preview what will be published:
npm pack --dry-run
Publishingโ
- Log in to your npm account:
npm login
- Verify your package contents:
npm pack --dry-run
- Publish:
npm publish
For scoped packages that should be public:
npm publish --access public
- Verify on
https://www.npmjs.com/package/<your-package-name>
Pre-publish Checklistโ
Before every publish, verify:
-
versionis bumped appropriately (see Versioning) -
filesfield includes all necessary files -
npm pack --dry-runshows only intended files - Tests pass
- Build output is up to date
- README is accurate and helpful
Automating with a Prepublish Scriptโ
Add a build step that runs automatically before publishing:
{
"scripts": {
"prepublishOnly": "npm run build && npm test"
}
}
This ensures you never publish stale or broken code.