How to use libraries with npm?

Abstract: Resolve dependency management issues by installing libraries via npm to automatically update package.json and isolate project requirements.

Created: 2026-08-03 by
To use libraries with npm, first install the package in your project directory using the command npm install <package-name>. This adds the library to your node_modules folder and records it as a dependency in your package.json file. You can then import or require the module in your JavaScript files to access its functionality, ensuring that your environment supports the module type such as CommonJS or ES modules.

Understanding npm and Package Management

npm stands for Node Package Manager and serves as the default package manager for Node.js. It allows developers to share, reuse, and manage code dependencies efficiently. When you work on a Node.js application, you rarely write every line of code from scratch. Instead, you rely on libraries created by the community to handle common tasks like HTTP requests, data validation, or user interface rendering. The core concept revolves around the package.json file. This manifest file lives in the root of your project and lists all the dependencies required for the application to run. It also specifies the version ranges for each library, which helps maintain consistency across different development environments. By managing these dependencies through npm, you ensure that anyone cloning your repository can replicate your exact setup by simply running an installation command. This approach prevents the "it works on my machine" problem. When you commit your package.json and package-lock.json files to version control, other developers or deployment servers know exactly which versions of libraries are needed. The package-lock.json file is particularly important because it locks down the exact versions of all installed packages, including nested dependencies, guaranteeing deterministic builds.

Installing Libraries via Command Line

The primary method for adding a library is through the terminal or command prompt. Navigate to your project's root directory where your package.json file resides. Then, execute the install command followed by the name of the package you wish to add. For example, to add a popular utility library, you might run:
npm install lodash
By default, this command installs the latest stable version of the package. It downloads the code into a hidden folder named node_modules within your project directory. Simultaneously, it updates your package.json file under the dependencies section, adding an entry like "lodash": "^4.17.21". The caret symbol indicates that npm should accept any minor or patch version updates that do not break compatibility, which is standard practice for production dependencies. If you are developing a tool that will be used globally, such as a command-line interface script, you might need the global flag. However, for most application development, local installation is preferred. Global installations can lead to conflicts between projects requiring different versions of the same library. Keeping dependencies local ensures isolation and stability for each specific project. For testing purposes, you may want to save a package only in the devDependencies section. These are tools like linters, compilers, or test runners that are not needed when the application runs in production. You can achieve this by adding the --save-dev flag:
npm install jest --save-dev
This distinction is crucial for reducing the final bundle size in production environments and clarifying which packages are essential for runtime operation versus development workflow.

Importing and Using Modules

Once a library is installed, you must include it in your code to use its features. The method of inclusion depends on the module system supported by the library and your Node.js configuration. Historically, Node.js used the CommonJS module system, which relies on the require function. To use a library in this format, you assign the result of the require call to a variable:
const _ = require('lodash');
This syntax is still widely used and supported. If the library uses ES modules, which are becoming the standard in modern JavaScript, you should use the import statement instead. This requires your project to have "type": "module" set in your package.json or use files with the .mjs extension.
import _ from 'lodash';
Some libraries provide both formats, allowing you to choose based on your project structure. It is important to check the documentation of the specific library to see how it recommends integration. Incorrectly mixing module systems can lead to errors such as "Cannot find module" or unexpected behavior regarding exports and imports. When you reference the package name in your code, Node.js automatically resolves it from the node_modules folder. You do not need to specify the full path to the file. This resolution process looks at the main field in the library's own package.json to determine which file to load initially. Understanding this resolution mechanism helps in debugging issues where the wrong file might be loaded due to naming conflicts or incorrect exports.

Managing Updates and Security

Libraries are frequently updated to fix bugs and improve performance. You can update all installed packages to their latest compatible versions using the update command. This reads your package.json constraints and fetches newer versions if available.
npm update
However, relying solely on automatic updates can introduce breaking changes. It is often safer to review the changelog of major libraries before updating them in a production environment. You can also check for outdated packages specifically by running:
npm outdated
This command lists packages that have newer versions available, helping you stay current without immediately changing your codebase. Regular maintenance of dependencies is a best practice for security, as older versions may contain known vulnerabilities. npm provides audit tools to scan your dependencies for security issues, providing a report on potential risks associated with specific library versions.

Frequently Asked Questions

What is the difference between node_modules and package.json?

The node_modules folder contains the actual downloaded source code of your libraries, while package.json is a text file that lists the names and version requirements of those libraries. You should never commit node_modules to version control because it is large and redundant; others can recreate it using package.json.

How do I remove a library from my project?

You can uninstall a package by running npm uninstall <package-name>. This removes the folder from node_modules and deletes the entry from your package.json dependencies. If you previously saved it as a dev dependency, use npm uninstall <package-name> --save-dev to clean up that section as well.

Why does npm install take so long?

Installation speed can vary based on network connectivity and the number of dependencies. Large projects with deep dependency trees require downloading many small packages. Using a faster internet connection or configuring an npm cache, as discussed in related Docker optimization guides, can significantly reduce installation times.

Can I use npm packages in browser-based JavaScript?

Not directly, as Node.js specific APIs are not available in browsers. However, you can use bundlers like Webpack or Vite to package npm libraries into browser-compatible JavaScript files. Some lightweight libraries are designed to work in both environments, but most backend-focused packages require a build step for frontend usage.

What happens if I delete node_modules by accident?

If you delete the node_modules folder, your application will stop working until you reinstall the dependencies. Simply running npm install again will restore the folder based on your package-lock.json file, ensuring you get the exact same versions that were previously installed.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More