npm basics
Installation
npm comes pre-installed with Node.js. To check if you have npm installed:
npm -v
To update npm to the latest version:
npm install -g npm@latestnpm install -g npm@latest
Initializing a Project
npm initnpm init
For a quick start with default values:
npm init -ynpm init -y
Installing Packages
Install a package and add to dependencies
npm install package-namenpm install package-name
# or
npm i package-name
Install a package and add to devDependencies
npm install package-name --save-devnpm install package-name --save-dev
# or
npm i package-name -D
Install a specific version of a package
npm install package-name@versionnpm install package-name@version
Install packages globally
npm install -g package-namenpm install -g package-name
Uninstalling Packages
npm uninstall package-namenpm uninstall package-name
To remove from devDependencies:
npm uninstall package-name --save-devnpm uninstall package-name --save-dev
To uninstall a global package:
npm uninstall -g package-namenpm uninstall -g package-name
Updating Packages
To update all packages in package.json:
npm updatenpm update
To update a specific package:
npm update package-namenpm update package-name
Listing Packages
List installed packages:
npm listnpm list
List global packages:
npm list -g --depth 0npm list -g --depth 0
Running Scripts
Run a script defined in package.json:
npm run script-namenpm run script-name
Common built-in scripts:
npm startnpm start
npm test
npm run build
Managing the package.json File
View package.json contents:
npm config listnpm config list
Set a config option:
npm config set key valuenpm config set key value
Get a config option:
npm config get keynpm config get key
Publishing Packages
Login to npm:
npm loginnpm login
Publish a package:
npm publishnpm publish
Versioning
Increment version and create a git tag:
npm version patch # 1.0.0 -> 1.0.1npm 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
Auditing for Vulnerabilities
npm auditnpm audit
To automatically fix vulnerabilities:
npm audit fixnpm audit fix
Clearing npm Cache
npm cache clean --forcenpm cache clean --force
Viewing Package Information
npm view package-namenpm view package-name
To view all versions of a package:
npm view package-name versionsnpm view package-name versions
Remember to always keep your npm and Node.js versions up to date, and regularly audit your projects for potential security vulnerabilities. The npm ecosystem is vast and constantly evolving, so staying informed about best practices and new features is crucial for efficient package management.