Using npx
Imagine you want to try out a new tool, but you don't want to install it globally because you might only use it once. Or you're working on a project and need to run a command from a package that isn't installed. That's where **npx** comes to the rescue!
What is npx?
npx is a tool that comes with npm (since npm v5.2.0) that lets you run Node.js packages without installing them globally. It executes package binaries either from the local `node_modules` or directly from the npm registry.
Think of npx as a "try before you buy" tool. You can run any package command without permanently installing it.
Why Use npx?
- Run one-off commands without polluting global installs.
- Always use the latest version of a tool.
- Easily run binaries from locally installed packages.
- Test different package versions quickly.
Basic Usage
To run a package with npx, simply prefix the command with `npx`:
npx cowsay Hello WorldIf `cowsay` isn't installed, npx will temporarily download it, run it, and then discard it. You'll see a fun ASCII cow saying "Hello World".
Running a Specific Version
You can also specify a version:
npx cowsay@1.5.0 HelloRunning Local Binaries
If you have a package installed locally (in `node_modules`), you can run its binary with npx without having to type the full path:
npx eslint src/This will use the `eslint` binary from your local `node_modules/.bin` folder.
Common npx Use Cases
| Command | Description |
|---|---|
| `npx create-react-app my-app` | Create a new React app without installing globally. |
| `npx http-server` | Start a simple static server. |
| `npx json-server db.json` | Start a fake REST API from a JSON file. |
| `npx sequelize-cli init` | Initialize Sequelize ORM. |
How npx Works
- First, npx checks if the command exists locally (`./node_modules/.bin`).
- If not, it checks if it's installed globally.
- If still not found, it downloads the package from the npm registry, runs it, and then discards it (unless you use `--no-install`).
Options
| Option | Description |
|---|---|
| `--no-install` | Only run if the package is already installed (don't download). |
| `--ignore-existing` | Always download a fresh copy, even if already installed. |
| `-p` | Specify the package to install (useful when the command name differs). |
Example with `-p`:
npx -p @vue/cli vue create my-app<!-- This installs the @vue/cli package and runs the `vue` command -->Two Minute Drill
- npx runs Node.js packages without installing them globally.
- Perfect for one-off commands or trying out tools.
- It can run binaries from local `node_modules` or download temporarily.
- Common uses: `create-react-app`, `http-server`, `json-server`.
- Comes bundled with npm (v5.2+).
Need more clarification?
Drop us an email at career@quipoinfotech.com
