NPM (Node Package Manager) is the default package manager for Node.js. It serves two primary functions:
package.json
file.To check the installed version of NPM, use the following command:
npm --version
To create a package.json
file for a new Node.js project, run:
npm init
You will be prompted to enter details like the project name, version, and description. For a quicker setup with default values, use:
npm init -y
To install a package and add it to the dependencies
section of package.json
,
use:
npm install <package-name>
To install a package as a development dependency, use:
npm install <package-name> --save-dev
To update a specific package to the latest version:
npm update <package-name>
To update all packages listed in package.json
:
npm update
To install all the dependencies listed in package.json
, use:
npm install
To run a script defined in the scripts
section of package.json
, use:
npm run <script-name>
For example, to start a development server with a script called start
, you
would run:
npm run start
To remove a package and also remove it from package.json
, use:
npm uninstall <package-name>
To uninstall a package but keep it in package.json
, use:
npm uninstall <package-name> --no-save
To get detailed information about a package, including its dependencies, version, and more:
npm info <package-name>
To search for packages in the NPM registry:
npm search <query>
To check for vulnerabilities in your dependencies:
npm audit
To fix vulnerabilities:
npm audit fix
NPM Workspaces allow you to manage multiple packages within a single repository.
Define Workspaces in package.json
:
{
"workspaces": ["packages/*"]
}
Run Commands Across All Workspaces:
npm run <script> --workspace <workspace-name>
Scripts in package.json
allow you to automate common tasks.
Example scripts
Section:
"scripts": {
"start": "node app.js",
"test": "mocha test/",
"build": "webpack"
}
Run start
Script:
npm start
Create a Package:
package.json
file.Use the following command to publish:
npm publish
Scope Packages:
Use scoped packages to publish under a specific namespace, e.g.,
@username/package-name
.
npm publish --access public
Install Package Globally:
npm install -g <package-name>
This makes the package available anywhere on your system.
Install Package Locally:
npm install <package-name>
This installs the package in the node_modules
directory of your project.
To view or modify your NPM configuration settings:
View Configuration:
npm config list
Set a Configuration Value:
npm config set <key> <value>
View Global Configuration File:
npm config edit
Issue: npm install
Fails
Solution: Check for missing or incorrect permissions, update NPM, or clear the cache:
npm cache clean --force
Issue: Dependency Conflicts
Solution: Resolve version conflicts by reviewing the package.json
or
using npm outdated
to check for updates.
npm outdated