npm package installation and uninstallation commands for global and local modules
NPM Basics: Installing and Uninstalling Packages
NPM (Node Package Manager) is a critical tool for managing dependencies in JavaScript projects. It allows developers to install, update, and remove packages efficiently. This guide focuses on the core commands for installing and uninstalling packages, distinguishing between global and local modules.
Installation Commands
The npm install command is the primary tool for adding packages to a project. It can be used with various flags to control behavior.
Basic Installation:
npm install <package-name>This installs the package locally in the project’s
node_modulesdirectory. The package is recorded in thepackage.jsonfile.Saving to
package.json:npm install <package-name> --saveAdds the package to the project’s
package.jsonfile, ensuring it is included in the project’s dependencies.Skipping
package.json:npm install <package-name> --no-saveInstalls the package without updating
package.json.Installing Multiple Packages:
npm install package1 package2Installs multiple packages simultaneously.
Uninstallation Commands
The npm uninstall command removes packages from a project. It can also be used to remove packages from global or local installations.
Removing a Package from a Project:
npm uninstall <package-name>Deletes the package from
node_modulesand updatespackage.json.Removing a Package from Global Installation:
npm uninstall -g <package-name>Removes the package from the global npm registry.
Removing a Package from Local Installation:
npm uninstall --save <package-name>Removes the package from
package.jsonandnode_modules.Removing a Package Without Updating
package.json:npm uninstall --no-save <package-name>Removes the package from
node_modulesbut leavespackage.jsonunchanged.
Global vs Local Modules
NPM packages can be installed in two modes: global or local.
Global Modules:
Packages installed withnpm install -gare system-wide and available to all users. They are stored in thenode_modulesdirectory of the global npm registry.npm install -g <package-name>Local Modules:
Packages installed withnpm installare confined to the current project. They are stored in the project’snode_modulesdirectory and are not visible to other projects.npm install <package-name>
Best Practices
- Use
--savefor dependencies: Always use--saveto ensure packages are included inpackage.json. - Avoid global installations: Global packages can be accidentally installed on multiple machines.
- Check
package.json: Verify installed packages withnpm listto ensure consistency across environments.
By mastering these commands, developers can efficiently manage their project dependencies and avoid conflicts between global and local installations.