| |

npm 27 ๐ŸŒ Cheatsheet

โฑ๏ธ Estimated read: 5 min | |

A quick-reference for npm commands, configuration, and dependency resolution. Organized for lookup, not for reading.


Core Commands

CommandPurpose
npm initCreate package.json interactively
npm init -yCreate with defaults
npm installInstall all dependencies
npm install <pkg>Install and save to dependencies
npm install <pkg>@<ver>Install specific version
npm install -D <pkg>Install as devDependency
npm install -g <pkg>Install globally
npm uninstall <pkg>Remove package
npm updateUpdate within semver ranges
npm outdatedList outdated packages
npm lsShow dependency tree
npm explain <pkg>Why is this installed? (alias: npm why)
npm dedupeFlatten duplicate dependencies
npm pruneRemove extraneous packages
npm ciClean install from lockfile
npm run <script>Run a script
npm startRun start script (no run needed)
npm testRun test script (no run needed)

package.json Fields

FieldPurpose
namePackage name (lowercase, no spaces)
versionSemver (x.x.x)
privatePrevent accidental publish
mainCJS entry point
moduleESM entry point (bundler convention)
typesTypeScript declarations
exportsConditional entry-point map
filesAllowlist of published files
scriptsNamed commands
dependenciesRuntime deps
devDependenciesBuild/test deps
peerDependenciesHost package expectations
peerDependenciesMetaMark peers as optional
overridesForce transitive versions
workspacesMonorepo directories
enginesNode/npm version requirements
publishConfigPublish-time settings (registry, access)

Semver Ranges

RangeMeaning
1.2.3Exact
~1.2.3Patch updates only (>=1.2.3 <1.3.0)
^1.2.3Minor updates (>=1.2.3 <2.0.0)
1.2.xAny patch
* or ""Any version
>=1.2.3 <2.0.0Range
1.2.3 - 2.0.0Inclusive range
latestThe latest dist-tag

Publishing

CommandPurpose
npm loginAuthenticate with registry
npm whoamiShow logged-in user
npm publishPublish package
npm publish --access publicPublish scoped package as public
npm publish --tag nextPublish under custom dist-tag
npm unpublish <pkg>@<ver>Remove version (restricted)
npm deprecate <pkg> "msg"Mark as deprecated
npm deprecate <pkg> ""Undeprecate
npm owner ls <pkg>List maintainers
npm owner add <user> <pkg>Add maintainer
npm owner rm <user> <pkg>Remove maintainer
npm dist-tag ls <pkg>List dist-tags
npm dist-tag add <pkg>@<ver> <tag>Move a tag
npm dist-tag rm <pkg> <tag>Remove a tag
npm packCreate tarball
npm pack --dry-runList tarball contents without writing

Security

CommandPurpose
npm auditReport vulnerabilities
npm audit --audit-level=moderateFail on moderate+
npm audit --omit=devSkip devDependencies
npm audit fixFix within semver ranges
npm audit fix --forceFix including major changes
npm audit fix --dry-runPreview fixes
npm token listList access tokens
npm token revoke <id>Revoke a token

Configuration

FileScope
Project .npmrcCurrent project
User ~/.npmrcCurrent user
Global $PREFIX/etc/npmrcAll users
Builtinnpm installation

Precedence

CLI flags > environment > project .npmrc > user .npmrc > global .npmrc > builtin > defaults

Common .npmrc Keys

KeyPurpose
registry=https://...Default registry
@scope:registry=https://...Scoped registry
//host/:_authToken=${NPM_TOKEN}Scoped auth token
save-exact=truePin exact versions
engine-strict=trueEnforce engines
strict-peer-deps=trueFail on peer conflicts
fund=falseDisable funding messages

Config Commands

CommandPurpose
npm config get <key>Read effective value
npm config set <key> <val>Write to user config
npm config delete <key>Remove setting
npm config listShow all config

Dependency Resolution

Peer Dependencies

{
  "peerDependencies": { "react": "^18.0.0 || ^19.0.0" },
  "peerDependenciesMeta": {
    "chalk": { "optional": true }
  }
}
SituationBehavior
Peer absent, not optionalERESOLVE (npm 7+)
Peer absent, optional: trueInstall succeeds
Peer present, incompatibleERESOLVE
--legacy-peer-depsSkip peer checks (last resort)
--strict-peer-depsFail on any conflict

Overrides

{
  "overrides": {
    "semver": "7.5.2",
    "@some/cli": { "semver": "7.5.2" },
    "ejs@2.7.4": "3.1.10",
    "react": "$react"
  }
}
FormScope
"pkg": "1.2.3"Entire tree
"parent": { "pkg": "1.2.3" }Only under parent
"pkg@1.0.0": "1.2.3"Only when resolved version is 1.0.0
"pkg": "$pkg"Match root dependency

Workspaces

CommandPurpose
npm init -w ./packages/aCreate a workspace
npm installInstall all, symlink workspaces
npm install <dep> -w <name>Add dep to one workspace
npm install <ws> -w <name>Add local workspace as dep
npm run <script> -w <name>Run script in one workspace
npm run <script> --workspacesRun in all workspaces
--if-presentSkip workspaces without the script
npm publish -w <name>Publish one workspace
npm publish --workspacesPublish all

Root package.json

{
  "private": true,
  "workspaces": ["packages/*", "apps/*"]
}

Hoisting

SituationResult
Compatible versionsHoisted to root node_modules
Incompatible versionsNested in the package that needs it
Undeclared importWorks via hoisting (phantom dependency)

Scoped Packages

CommandPurpose
npm init --scope=@orgInitialize with scope
npm publish --access publicPublish scoped package as public
npm publishPublish as private (paid account)
npm access get status @org/pkgCheck access level
npm access set status=public @org/pkgMake public
npm access grant read-write @org:team @org/pkgGrant team access
npm access revoke @org:team @org/pkgRevoke access

Scope to Registry

@myorg:registry=https://npm.company.com/
//npm.company.com/:_authToken=${NPM_TOKEN}

Lifecycle Scripts

ScriptRuns When
preinstallBefore install
installDuring install
postinstallAfter install
prepublishOnlyBefore npm publish only
prepareBefore pack/publish, on local install, on git install
prepackBefore tarball creation
postpackAfter tarball creation
preversionBefore npm version
versionAfter version bump
postversionAfter commit and tag

Debugging

CommandPurpose
npm ls <pkg>Show resolved version
npm explain <pkg>Why is it installed?
npm ls --all | grep dedupedFind duplicates
npm install --dry-runPreview install
npm cache clean --forceClear cache
npm doctorCheck environment

npx

CommandPurpose
npx <pkg>Run a package binary
npx <pkg>@<ver>Run a specific version
npx --no-install <pkg>Fail if not installed locally
npx -p <pkg> <cmd>Make package available to command

Gotchas

TrapReality
npm install installs exact versionsIt respects semver ranges from package.json
npm ci is the same as installci requires lockfile, is faster, fails on mismatch
--legacy-peer-deps is a fixIt hides conflicts; fix them properly
npm update crosses major versionsNo; respects package.json ranges
latest tag is the highest versionNo; it’s whatever latest points to
devDependencies are omitted in productionOnly if NODE_ENV=production or --omit=dev
files field includes everythingIt’s an allowlist; only listed files ship
.npmignore overrides filesfiles takes precedence
Token in .npmrc is safeOnly if scoped to host and gitignored
postinstall runs on npm ciYes, unless --ignore-scripts

One-Page Flow

INIT โ†’ INSTALL โ†’ CODE โ†’ TEST โ†’ PUBLISH

INIT
  npm init -y
  npm install <deps>
  npm install -D <devdeps>

RESOLVE
  npm ls <pkg>          (what version?)
  npm explain <pkg>     (why installed?)
  overrides             (force version)
  peerDependencies      (declare host contract)

PUBLISH
  npm pack --dry-run    (what ships?)
  npm version patch     (bump + tag)
  npm publish           (upload)
  npm audit             (check CVEs)

MONOREPO
  workspaces field      (link packages)
  -w <name>             (target one)
  --workspaces          (target all)
  build tool            (task ordering)

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!