npm global: global install usage tips
NPM Core Commands
npm global: Global Install Usage Tips
Key Concepts
The npm global command is essential for installing packages that are meant to be used system-wide, rather than per-project. These packages are typically distributed via the npm registry and are installed in a global directory, such as ~/.npm/_global/ by default.
Usage Tips
1. Check Installed Packages
Before installing a global package, verify which packages are already installed to avoid conflicts. Use the following command:
npm list --global
This command lists all globally installed packages along with their versions.
2. Install Global Packages
To install a package globally, use the -g flag with npm install. For example:
npm install -g webpack
This installs webpack as a system-wide tool, allowing it to be used across multiple projects.
3. Specify Installation Path
By default, npm install -g installs packages in ~/.npm/_global/. To customize the installation location, use the --global flag with a custom path:
npm install -g --global /path/to/global/directory
This is useful for environments where the global directory is not the default.
4. Manage Dependencies
Global packages often depend on other packages. Ensure dependencies are resolved correctly by running:
npm install -g --save-dev <package-name>
This adds the package as a development dependency, ensuring it’s included in the project’s package.json.
5. Uninstall Global Packages
To remove a globally installed package, use:
npm uninstall -g <package-name>
This deletes the package from the global directory, freeing up space and avoiding conflicts.
Best Practices
- Avoid Over-Global Installation: Only install packages that are universally required (e.g., build tools, linters).
- Use
--save-dev: For development tools, use--save-devto prevent accidental inclusion in production builds. - Check for Conflicts: Ensure global packages do not conflict with project-specific packages by using
npm lsto compare dependencies.
Conclusion
The npm global command is a powerful tool for managing system-wide dependencies. By following best practices and understanding its nuances, developers can efficiently install and manage global packages without compromising project integrity.