Working with npm Packages
Explore how to efficiently work with npm packages in Node.js projects. Understand the differences between local and global installations, manage dependencies through package.json, and practice using the axios library to make HTTP requests. Gain the skills necessary to simplify project setup and maintain consistent environments.
In the previous lesson, we explored npm and the package.json file, which helps organize a project’s metadata and scripts. However, the true strength of npm lies in its ability to manage dependencies—external libraries that enhance our projects by providing ready-made solutions for common tasks, saving both time and effort.
For example:
chalkfor styling terminal text with colors.axiosfor simplifying HTTP requests.jsonwebtokenfor secure, token-based authentication.
Note: package import style (
requirevsimport) can vary by package version and module format.
Installing packages
Before using an external library in our project, we must install it. npm makes this process seamless, whether installing locally for a specific project or globally for system-wide tools.
Installing a package locally
Local installations are tied to a specific project and are the most common way to use npm packages. They allow us to include libraries specific to our project's needs without affecting other projects. For example, we can install the axios library to simplify making HTTP requests in our application.
npm install axios
After running this command, the following happens:
-
npm adds the
axioslibrary to anode_modulesdirectory in our project folder. This folder contains all locally installed packages and their dependencies. -
By default,
npm install <package>updates thepackage.jsonfile, adding the package to the dependencies section. (Flags like--save-devor--no-savechange this behavior.):"dependencies": {