How to Enable npm
npm
(Node Package Manager) is Node.js's package management tool and its default package manager. It is used to install, share, and manage JavaScript packages and is one of the largest open-source libraries globally. Using npm
can help developers easily manage project dependencies and enhance development efficiency.
Enabling npm
Node.js installed through ServBay comes with npm
enabled by default. If you find that npm
is not enabled or needs updating, you can follow these steps.
Confirming npm Installation
Open the terminal and enter the following command to check the
npm
version number:bashnpm -v
1Example output:
bash9.1.0
1
Updating npm
If you need to update npm
, you can update it with the following command:
npm install -g npm
Confirm the version number again:
npm -v
Benefits of Using npm
The main advantage of npm
is its globally largest open-source library and convenient package management capabilities. Here are some practical examples of using npm
:
Initializing a Project
Use npm
to initialize a new Node.js project:
npm init
This will guide you to create a new package.json
file containing basic information and dependencies of the project.
Installing Dependencies
Use npm
to install project dependencies:
npm install
This will install all dependencies based on the package.json
file.
Adding a Dependency
Add a new dependency package:
npm install lodash --save
This will install the lodash
package and update the package.json
file.
Removing a Dependency
Remove a dependency package:
npm uninstall lodash --save
This will remove the lodash
package from the project and update the package.json
file.
Updating Dependencies
Update all dependencies in the project:
npm update
Using npm Scripts
npm
allows defining scripts in the package.json
file, making it convenient to execute common commands. For example, add the following scripts to the package.json
file:
"scripts": {
"start": "node app.js",
"test": "mocha"
}
2
3
4
Then you can run these scripts with the following commands:
npm start
npm test
2
Common Commands
Install a Global Package:
bashnpm install -g <package-name>
1For example, install
nodemon
:bashnpm install -g nodemon
1View Global Packages:
bashnpm list -g --depth=0
1Clean Cache:
bashnpm cache clean --force
1
By using npm
, developers can easily manage project dependencies, quickly install and update packages, and thus improve overall development efficiency.