npm Essentials: Installing and Managing Packages
A quick guide on basic npm commands and usage
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 package-name@1.2.3- 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=0Common Issues
- Permissions errors: You might need to use
sudoon 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 installto recreate the folder
Additional Notes
- The
node_modulesfolder contains all installed packages and should be in your.gitignore package.jsonlists your dependencies and project metadatapackage-lock.jsonensures consistent installations across machinesGlobal installation: Use the
-gflag to install packages globally:npm install -g package-namenpm scripts: Define custom commands in the "scripts" section of package.json:
"scripts": { "start": "node index.js", "test": "jest", "build": "webpack" }Run them with
npm run script-name(or justnpm startfor the start script)