Overview
npm (Node Package Manager) is the default package manager for Node.js. It allows you to install, share, and manage dependencies in your JavaScript projects.
Steps
- Initialize a new npm project:
npm init
# For defaults without prompts
npm init -y
- Install a package:
# Add to dependencies (runtime)
npm install package-name
# or shorthand
npm i package-name
# Add to devDependencies (development tools)
npm install package-name --save-dev
# or shorthand
npm i package-name -D
- Install a specific version:
npm install [email protected]
- Install all dependencies from package.json:
npm install
- Update packages:
# Update all packages
npm update
# Update specific package
npm update package-name
- Remove a package:
npm uninstall package-name
- List installed packages:
npm list
# Just top-level packages
npm list --depth=0
Common Issues
- Permissions errors: You might need to use
sudo
on Unix-based systems or adjust permissions - Package lock conflicts: If working in a team, merge conflicts in package-lock.json can occur
- Dependency version issues: Some packages may have incompatible version requirements
- “node_modules is missing”: Run
npm install
to recreate the folder
Additional Notes
- The
node_modules
folder contains all installed packages and should be in your.gitignore
package.json
lists your dependencies and project metadatapackage-lock.json
ensures consistent installations across machines- Global installation: Use the
-g
flag to install packages globally:npm install -g package-name
- npm scripts: Define custom commands in the “scripts” section of package.json:
Run them with
"scripts": { "start": "node index.js", "test": "jest", "build": "webpack" }
npm run script-name
(or justnpm start
for the start script)