Local vs. Global Installation of nodejs package - npx use case
Suppose you have installed tsc package locally in your project (npm i tsc). Note here we have not used -g flag (global installation).
Then you can run tsc via "npx tsc" command. Using npx tsc instead of tsc has a few benefits related to how Node.js and npm manage dependencies and executables:
1. Local vs. Global Installation
-
Global Installation: If you install TypeScript globally using
npm install -g typescript, you can use thetsccommand directly from anywhere. However, this means you need to manage the global TypeScript version, which can lead to version mismatches across different projects. -
Local Installation: If you install TypeScript locally in your project using
npm install typescript --save-dev, thetsccommand is placed innode_modules/.bin, which is not globally available in your terminal.
2. Using npx
npx is a tool that comes with npm (version 5.2.0 and higher) and is designed to execute binaries from the node_modules/.bin directory. It allows you to run commands from locally installed packages without needing to install them globally.
Benefits of Using npx tsc:
- Consistency: Ensures you are using the project-specific version of TypeScript, avoiding potential version conflicts between projects.
- No Global Installation Required: You don't need to install TypeScript globally, which keeps your global environment clean.
- Ease of Use: You don't need to remember to add
./node_modules/.binto your PATH.npxhandles this automatically.
Practical Example
-
Local Installation of TypeScript:
npm install typescript --save-dev -
Using
npx tsc:npx tsc
Why Not Just Use tsc?
If you run tsc without npx in a project with only a local installation of TypeScript, you'll get an error like command not found: tsc. This is because the tsc command is not available globally unless you have installed TypeScript globally.