In this lesson, you will learn why relying on globally installed packages can break your applications and how to ensure your project always uses the specific versions it needs.
The Problem with "Global"
When you install a package globally (using npm install -g <package-name>), Node.js places it in a system-wide folder. While this might seem convenient for command-line tools, it creates a "hidden dependency" nightmare.
If Project A requires lodash@3.0.0 and Project B requires lodash@4.0.0, but you installed lodash globally on your machine, your projects will fight over which version to use. Even worse, if you move your code to a colleague's computer or a server, it might fail because they lack that specific global installation. Your project's success shouldn't depend on how your computer is configured!
Prioritizing Local Resolution
Node.js is designed to look for modules in a specific order. When you require() or import a package, Node.js starts by checking the node_modules folder inside your project directory. By keeping everything local, you ensure your project is self-contained.
If you need a command-line tool, don't rely on a global version. Instead, install it locally as a devDependency and run it using npx.
Example:
Instead of running eslint (which assumes a global install), use:
# This installs it locally to your project
npm install eslint --save-dev
# This ensures you are using the local version defined in your project
npx eslint .
By using npx, you force Node.js to look at your local node_modules folder first. This approach guarantees that every developer on your team is using the exact same version of the tool, regardless of what is installed on their global system path. This eliminates "it works on my machine" bugs and keeps your environment clean and predictable.
Key Takeaway: Always prioritize local project dependencies over global installations to ensure consistent, portable, and conflict-free module resolution.