Managing npm Packages

1. Initializing Package

CommandAction
npm initInteractive wizard
npm init -yAccept defaults
npm init <initializer>Run create-<name> (e.g. npm init vite)

2. Installing Packages

CommandEffect
npm installInstall from package.json
npm i pkgAdd to dependencies
npm i pkg@1.2.3Specific version
npm ciClean install from lockfile (CI)
npm i --omit=devProduction-only deps

3. Installing Dev Dependencies

CommandEffect
npm i -D pkgAdds to devDependencies
npm i --save-dev pkgSame as above

4. Installing Global Packages

CommandNotes
npm i -g pkgInstalls to global prefix
npm ls -g --depth=0List global installs
npm uninstall -g pkgRemove global
Note: Prefer npx or local devDependencies over globals to avoid version drift.

5. Updating Packages

CommandEffect
npm outdatedShow available updates
npm updateUpdate within semver range
npm i pkg@latestBump to latest, update package.json
npx npm-check-updates -uBump all to latest

6. Removing Packages

CommandEffect
npm uninstall pkgRemove + update package.json
npm rm pkgAlias

7. Using npx for Package Execution

FormBehavior
npx cowsay hiRun binary, fetch if needed
npx -p pkg cmdSpecify package explicitly
npx pkg@1.2.3Pin version for one-off
npx -y create-react-app my-appSkip install prompt

8. Understanding Semantic Versioning (^, ~, exact)

RangeMatchesUse
1.2.3ExactStrict pin
^1.2.3>=1.2.3 <2.0.0Default; minor + patch updates
~1.2.3>=1.2.3 <1.3.0Patch updates only
1.xAny 1.y.zLoose
* / latestAnythingAvoid in apps
>=1.2 <2CompoundCustom range

9. Managing Lock Files

FilePurpose
package-lock.jsonPin transitive deps (commit it)
npm shrinkwrapPublishable lock for libs
npm ciStrict install from lock

10. Auditing Security

CommandEffect
npm auditShow vulnerabilities
npm audit fixAuto-fix within semver
npm audit fix --forceAllow breaking upgrades
npm audit --omit=devProduction only

11. Publishing Packages

Publish Workflow

  1. npm login
  2. Bump version: npm version patch|minor|major
  3. Build (if needed)
  4. npm publish (add --access public for scoped packages)
  5. npm dist-tag add pkg@1.2.3 latest
FieldUse
"private": truePrevent accidental publish
"files"Whitelist what gets published
.npmignoreExclude paths

12. Using Workspaces

Example: Monorepo workspaces

{
  "name": "monorepo",
  "private": true,
  "workspaces": ["packages/*", "apps/*"]
}
CommandEffect
npm i -w pkg-aInstall in specific workspace
npm run build -wsRun in all workspaces
npm run test -w pkg-aRun in one workspace