NPM logoNPMINTERMEDIATE

NPM Package Manager

NPM cheat sheet covering package.json config, dependency management, scripts, publishing, workspaces, and CLI command reference.

10 min read
npmpackage-managernodejspublishingworkspacesdependenciescli

Sign in to mark items as known and track your progress.

Sign in

Project Setup & Initialization

Initialize and configure new NPM projects

Initialize Project

Create a new package.json file

bash
# Interactive setup
npm init

# Quick setup with defaults
npm init -y

# Create with scope
npm init --scope=@mycompany

# Use create- starter
npm init react-app my-app
npm init vite@latest my-project

# Common init options
npm init -w packages/new-package  # In workspace
npm init --workspace=packages/api
🟢 Essential - Every project starts with npm init
💡 Use -y flag to skip questions and use defaults
📌 npm init <pkg> runs npm exec create-<pkg>
⚡ Set config defaults to save time
🔗 Related: npm config for default settings
initsetup

Package.json Structure

Essential fields in package.json

json
// package.json
{
  "name": "my-project",
  "version": "1.0.0",
  "description": "Project description",
  "main": "index.js",
  "type": "module",  // ES modules
  
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js",
    "test": "jest",
    "build": "webpack",
    "lint": "eslint ."
  },
  
  "keywords": ["nodejs", "api"],
  "author": "Your Name",
  "license": "MIT",
  
  "dependencies": {
    "express": "^4.18.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.0",
    "jest": "^29.0.0"
  }
}
🟢 Essential - package.json is the project manifest
💡 Use "type": "module" for ES modules
📌 Scripts are shortcuts for common commands
⚡ "files" field controls what gets published
⚠️ Name must be lowercase and URL-safe
package.jsonconfig

NPX - Package Execution

Execute packages without installing globally

bash
# Run package without installing
npx create-react-app my-app
npx eslint .
npx prettier --write .

# Run specific version
npx node@14 index.js
npx webpack@4 build

# Run from GitHub
npx github:user/repo

# Run local binary
npx mocha test/

# Clear npx cache
npx clear-npx-cache
🟢 Essential - Run packages without global install
💡 Great for one-time use tools
⚡ Always uses latest version unless specified
📌 Packages are temporarily downloaded and cached
🔗 Related: npm exec is the same as npx
npxexecution

Package Management

Install, update, and remove packages

Installing Packages

Add dependencies to your project

bash
# Install all dependencies
npm install
npm i  # shorthand

# Install specific package
npm install express
npm install express@4.18.0  # specific version

# Install as dev dependency
npm install --save-dev nodemon
npm i -D jest  # shorthand

# Install globally
npm install -g typescript
npm i -g pm2

# Install from git
npm install git+https://github.com/user/repo.git
npm install github:user/repo
🟢 Essential - Most common NPM operation
💡 npm ci is faster for automated environments
📌 Use -D for dev-only tools (testing, building)
⚠️ Global installs can cause version conflicts
⚡ --production skips devDependencies
installpackages

Updating Packages

Keep dependencies up to date

bash
# Check outdated packages
npm outdated
npm outdated -g  # Global packages

# Update package
npm update express
npm update  # Update all packages

# Update to latest (ignoring semver)
npm install express@latest

# Interactive update
npx npm-check -u
npx npm-check-updates

# Update package.json version ranges
npx npm-check-updates -u
npm install  # Install updated versions
💡 npm update respects semver ranges in package.json
⚠️ audit fix --force may introduce breaking changes
📌 Use npm-check-updates for major version updates
🟢 Essential - Keep dependencies secure and updated
⚡ npm dedupe reduces duplication in node_modules
updatemaintenance

Removing Packages

Uninstall and clean up packages

bash
# Remove package
npm uninstall express
npm remove express  # Alias
npm rm express  # Short alias

# Remove dev dependency
npm uninstall -D nodemon

# Remove global package
npm uninstall -g typescript

# Remove without updating package.json
npm uninstall express --no-save

# Clean cache
npm cache clean --force
npm cache verify
💡 npm prune removes packages not in package.json
📌 Cache clean might be needed for stubborn issues
⚠️ Removing node_modules is the nuclear option
🟢 Essential - Keep project clean and lean
🔗 Related: npx depcheck finds unused packages
uninstallcleanup

Scripts & Task Running

Define and run npm scripts

Running Scripts

Execute scripts defined in package.json

bash
# Run scripts from package.json
npm run build
npm run test
npm run dev

# Special scripts (no 'run' needed)
npm start
npm test
npm stop
npm restart

# Pass arguments to scripts
npm run test -- --watch
npm run build -- --production

# List available scripts
npm run

# Run pre/post scripts
# pretest runs before test
# postbuild runs after build
🟢 Essential - Scripts automate common tasks
💡 Use -- to pass flags to the underlying command
📌 pre/post scripts run automatically
⚡ Special scripts (start, test) don't need "run"
🔗 Related: concurrently, npm-run-all for parallel
scriptsrun

Environment & Config

Configure NPM behavior and environment

bash
# View config
npm config list
npm config get registry

# Set config
npm config set registry https://registry.npmjs.org/
npm config set save-exact true

# Delete config
npm config delete save-exact

# Edit config file
npm config edit

# Set for current command only
npm install --registry http://localhost:4873

# Environment variables
NODE_ENV=production npm run build
npm_config_production=true npm install
💡 Project .npmrc overrides user config
📌 Use npm config for persistent settings
⚠️ Don't commit auth tokens to .npmrc
🟢 Essential for CI/CD and private registries
🔗 Related: dotenv for environment variables
configenvironment

Publishing & Versioning

Publish packages and manage versions

Version Management

Semantic versioning and releases

bash
# Bump version (updates package.json)
npm version patch  # 1.0.0 -> 1.0.1
npm version minor  # 1.0.0 -> 1.1.0
npm version major  # 1.0.0 -> 2.0.0

# Specific version
npm version 1.2.3

# Prerelease versions
npm version prerelease  # 1.0.0 -> 1.0.1-0
npm version prerelease --preid=beta  # 1.0.1-beta.0

# With git tag
npm version patch -m "Release v%s"

# Without git tag
npm version patch --no-git-tag-version
🟢 Essential - Follow semantic versioning
💡 Major: breaking, Minor: features, Patch: fixes
📌 Version command creates git tag automatically
⚡ Use preversion script to run tests first
🔗 Related: standard-version, semantic-release
versionsemver

Publishing Packages

Publish to NPM registry

bash
# Login to registry
npm login
npm whoami  # Verify login

# Publish package
npm publish

# Publish with tag
npm publish --tag beta
npm publish --tag next

# Publish scoped package publicly
npm publish --access public

# Dry run (see what would publish)
npm publish --dry-run

# Pack for inspection
npm pack  # Creates .tgz file
🟢 Essential for package authors
💡 Use --dry-run to preview before publishing
⚠️ Unpublish only works within 72 hours
📌 Use "files" field to control published files
🔗 Related: np package for easier publishing
publishregistry

Security & Maintenance

Keep projects secure and well-maintained

Security Auditing

Find and fix security vulnerabilities

bash
# Run security audit
npm audit

# Show detailed report
npm audit --json

# Fix automatically
npm audit fix

# Force fixes (may break)
npm audit fix --force

# Audit production only
npm audit --omit=dev

# Set audit level
npm audit --audit-level=moderate
🟢 Essential - Security is critical
💡 Run audit regularly in CI/CD
⚠️ --force may introduce breaking changes
📌 Set audit-level to fail CI appropriately
🔗 Related: snyk, socket for advanced scanning
securityaudit

Package Information

Inspect and analyze packages

bash
# View package info
npm view express
npm view express version  # Latest version
npm view express versions  # All versions

# List installed packages
npm ls
npm ls --depth=0  # Top level only
npm ls express  # Find specific package

# Show package size
npm ls --prod --parseable | wc -l

# Find duplicate packages
npm dedupe --dry-run
npm find-dupes

# Package funding info
npm fund
npm fund express
💡 Use npm explain to understand dependencies
📌 npm fund shows open-source funding info
⚡ npm dedupe reduces duplicate packages
🟢 Essential for dependency management
🔗 Related: npm-check, npm-check-updates
infoanalysis

Workspaces & Advanced

Monorepo management with NPM workspaces

NPM Workspaces

Manage multiple packages in monorepo

bash
// Root package.json
{
  "name": "my-monorepo",
  "workspaces": [
    "packages/*",
    "apps/*"
  ]
}

# Install in workspace
npm install express -w packages/api
npm install -D jest --workspaces

# Run scripts in workspace
npm run build -w packages/core
npm run test --workspaces

# Execute in all workspaces
npm run build --workspaces --if-present

# Create new workspace
npm init -w packages/new-package
🔴 Advanced - Great for monorepos
💡 Workspaces share dependencies (hoisting)
📌 Use workspace: protocol for internal deps
⚡ Reduces duplication and install time
🔗 Related: lerna, nx for advanced monorepos
workspacesmonorepo

NPM Link & Local Dev

Link local packages for development

bash
# Link package globally
cd my-package
npm link

# Use linked package
cd my-app
npm link my-package

# Unlink
npm unlink my-package
cd my-package && npm unlink

# List linked packages
npm ls -g --depth=0 --link

# Link specific package
npm link ../local-package
💡 npm link creates symlinks for local dev
📌 Great for testing packages before publishing
⚠️ Remember to unlink when done
⚡ file: protocol copies, link: symlinks
🟢 Essential for package development
linkdevelopment

Cache & Performance

Manage NPM cache and improve performance

bash
# View cache info
npm cache ls
npm cache verify

# Clean cache
npm cache clean --force

# Offline install
npm install --offline

# Prefer offline
npm install --prefer-offline

# Cache location
npm config get cache

# Set cache folder
npm config set cache /path/to/cache
💡 Cache speeds up repeated installs
⚡ npm ci is much faster for CI/CD
📌 --prefer-offline uses cache when possible
🟢 Essential for CI/CD optimization
🔗 Related: yarn, pnpm for faster installs
cacheperformance