We have seen how to use NPM to install packages locally, which only affect our project. But it is also possible to install packages globally.
Global package installation in NPM refers to the action of installing a package in a system-wide accessible location, rather than installing it specifically in a project.
Global package installation in NPM is convenient at times. But it also has significant disadvantages, and it’s important to understand when it’s appropriate to use it (and use it prudently).
As a general rule, we should always use local packages and only use global packages when there is no other alternative. For example, in the case of command-line tools, if the author provides no other alternative.
Many of the cases where we previously had to use a global package can be solved with NPX. Read more at What is and how to use NPX
How to Install a Package Globally
Global package installation is a simple process. To perform a global installation, you must use the following command in your terminal:
npm install -g nombre_del_paquete
As we can see, the only difference is that we have added the -g parameter to indicate that we want the package to be installed globally.
NPM will download the package and install it in a global location, where Node.js can access it at any time. Usually in a specific folder on your system.
%USERPROFILE%\AppData\Roaming\npm\node_modules
/usr/local/lib/node_modules
In most cases, you will need administrator permissions (or superuser mode) to perform global installations on your system.
Advantages and Disadvantages
Global package installation offers several advantages and disadvantages for developers, which we must consider. In general, there are more disadvantages than advantages and unless absolutely necessary, we will prefer local packages.
Advantages
Universal Access: Once a package is installed globally, you can use it in any Node.js project or application on your machine. This avoids the need to install the same package over and over again in different projects, saving time and disk space.
Command-Line Tools: Many packages in NPM offer command-line tools that can be useful in daily development. Installing these packages globally allows access to these tools from anywhere on your system.
Disadvantages
Version Conflicts: The biggest disadvantage is that global installation can lead to version conflicts between different projects that use the same package. If one project requires a specific version of a package and another project requires a different version, well… 💥
Dependency on Local Environment: Globally installed packages may depend on local environment variables or specific locations on the system. This could cause problems if you share your code with other developers who have different configurations.
