npx 入门教程

不装全局就能跑命令行工具,以及 `npm exec` 与它的关系。

Beginner
Key Points`npx` 先在本地 `node_modules/.bin` 找,找不到就临时下载到缓存里执行,跑完不装进全局。

解决什么问题

Bash
# 老办法:为了跑一次就要装全局,还会污染全局版本
npm i -g create-vite
create-vite my-app

# 新办法:直接用,用完不留
npx create-vite my-app

npx ships with npm since 5.2. It looks in local node_modules/.bin, then the cache, then downloads temporarily. So the project's locked version wins, keeping behaviour reproducible.

常用姿势

Bash
# 跑一次性脚手架
npx create-vite@latest my-app
npx create-next-app@latest

# 指定版本
npx typescript@5.4 tsc --version

# 跑本地已装但没加进 scripts 的工具
npx eslint src/

# 跑 GitHub 上的包
npx github:user/repo

# 只下载不执行(配合 --no-install 可看会装什么)
npx --no-install eslint -v
Output
$ npx typescript@5.4 tsc --version
Version 5.4.5

参数怎么传

Bash
# npx 自己的参数放前面,传给工具的参数放后面
npx --yes create-vite my-app --template react

# --yes:跳过「需要下载,是否继续」的确认
# --package:显式指定包名,当命令名和包名不同时用
npx --package=@angular/cli ng new app
Packages fetched by npx do not appear in package.json, so another machine will not have them. Tools the project needs long-term belong in devDependencies with a scripts entry.

npm exec

Bash
# npx 就是 npm exec 的简写
npm exec -- create-vite my-app

# 差别:npm exec 需要 -- 分隔自己的参数和命令参数
npm exec --yes --package=typescript -- tsc --version
FormNote
npx foo简写,日常够用
npm exec foo完整命令,CI 里更明确
npm exec -- foo --bar-- 之后全传给工具

安全提醒

npx some-package means downloading and running a stranger's code. A one-letter typo (typosquatting) can execute something malicious. Run npm view <name> first to check the author, download count and publish date.

Friends & Partners