npm & npx
npm installs packages; npx runs package binaries without installing them.
Syntax
npm install <package>
npx <command>npm is the command-line tool that installs and manages packages. It talks to the npm registry, a huge public library of open-source code.
Common npm commands
npm install express— add a package.npm install— install everything in package.json.npm uninstall express— remove a package.
What is npx?
npx runs a package's command without installing it permanently — perfect for one-off tools like project generators.
Example
# Install a package into your project
npm install lodash
# Run a tool once without a permanent install
npx cowsay "Hello Node"
# Install a command-line tool globally
npm install -g nodemonWhen to use it
- A developer runs `npx create-react-app my-app` to scaffold a project without permanently installing a generator that would quickly become stale.
- A team uses `npm install --save-dev eslint` to add linting as a dev dependency so production Docker images stay lean.
- An automation script runs `npm ci` in CI instead of `npm install` to get a reproducible, faster install from package-lock.json.
More examples
Install a package
Shows the three main install modes: production dependency, dev dependency, and global tool.
# Install as a production dependency
npm install express
# Install as a dev dependency
npm install --save-dev jest
# Install globally
npm install -g typescriptRun a one-off tool with npx
Uses `npx` to execute a package binary without a global install -- it downloads and discards it after running.
# Scaffold a project without installing the generator globally
npx create-next-app@latest my-project
# Run a locally installed binary
npx jest --watchUseful npm commands
A cheat-sheet of common npm commands for managing and auditing a project's dependencies.
npm list # show installed packages
npm outdated # packages with newer versions
npm update # update within semver ranges
npm uninstall lodash # remove a package
npm audit # scan for known vulnerabilities
Discussion