Table of Contents

Install npm packages locally vs globally

When managing dependencies in a Node.js project, you often have a choice between installing packages globally and installing them locally within a project. Both approaches have their use cases and advantages, and you can run local packages using npx without installing them globally.

Global installation

Global installation installs a package in a central location on your system, making it accessible from any directory. This is often used for command-line tools that you want to use across multiple projects.

Command to install globally:

npm install -g <package-name>

Command to run it:

<package_name>

Use case: Useful for CLI tools that you want to use across different projects.
Access: You can run the command from anywhere in your system.
Versioning: One version installed for all projects, which can lead to version conflicts if different projects require different versions.

Local installation

npx is a command-line tool that comes with npm (version 5.2.0 and higher) that allows you to run locally installed packages as if they were installed globally.

Command install locally:

npm install <package_name>

Command to run with npx:

npx <package_name>

Use case: Ideal for project-specific dependencies or when you want to try a package without installing it.
Access: You can only run the command within the project where it's installed or explicitly specify the package with npx.
Versioning: Each project can have its own version of the package, reducing conflicts.

Comparison

  1. Flexibility: Local installation with npx offers more flexibility, as you can have different versions for different projects.
  2. Ease of use: Global installation is easier to use across multiple projects but might lead to version conflicts.
  3. Isolation: Using npx with local packages ensures that your project’s dependencies are isolated from other projects, leading to more predictable behavior.

Example

Suppose you want to use terser to minify files:

Global Installation

Install:

npm install -g terser 

and then run:

terser file.js -o file.min.js

Local Installation

Install:

npm install terser 

and then run within the project where terser is installed:

npx terser file.js -o file.min.js