npm Cheatsheet - Node.js Package Manager Reference

npm 是 Node.js 默认的包管理工具,最常用的命令和工作流都在这里了,快速查阅项目管理高频操作。

Languages·41 commands·Last updated 2026-07-21
Back to Languages

项目初始化 4

npm init -y
快速生成 package.json(全部默认值)
npm init
交互式逐项填写生成 package.json
npm init <initializer> [args]
用脚手架创建项目(如 npm init vite)
npm create <initializer>@latest
create 是 init 别名,等价于 npx create-<initializer>

安装与卸载 7

npm install
安装 package.json 中所有依赖
npm install <pkg>
安装并写入 dependencies
npm install -D <pkg>
安装到 devDependencies
npm install -g <pkg>
全局安装(可在任意目录使用)
npm install <pkg> --save-exact
锁定精确版本(不带 ^ 前缀,缩写 -E)
npm uninstall <pkg>
卸载依赖并从 package.json 移除
npm uninstall -g <pkg>
卸载全局安装的包

版本管理 6

npm install <pkg>@1.2.3
安装指定版本
npm install <pkg>@latest
安装或更新到最新版
npm install <pkg>@^1.0.0
按 semver 范围安装(插入号,允许小版本升级)
npm update [pkg]
更新依赖到符合 semver 的最新版
npm outdated
列出过时依赖(当前/期望/最新)
npm dedupe
去重依赖树,减少重复安装

脚本与运行 6

npm run <script>
运行 package.json 中的 scripts
npm start
运行 start 脚本(简写,无需 run)
npm test
运行 test 脚本(简写,等价 npm run test)
npm run
列出所有可用脚本
npx <command> [args]
临时执行本地或远程包(无需全局安装)
npm run <script> -- --port 8080
用 -- 透传后续参数给脚本

依赖查看 6

npm ls
查看依赖树
npm ls --depth=0
只看顶层依赖
npm ls <pkg>
查看某包是否安装及版本
npm why <pkg>
查看依赖被谁引入(npm 7+)
npm audit
扫描依赖安全漏洞
npm audit fix
自动修复可修复的漏洞

发布管理 5

npm version <patch|minor|major>
升级版本号并自动打 git tag
npm publish
发布包到 npm registry
npm publish --tag beta
发布到指定 dist-tag(如 beta)
npm deprecate <pkg>@<ver> "原因"
弃用某个版本并提示使用者
npm owner add <user> [<pkg>]
添加包维护者(npm owner ls 查看)

配置与缓存 7

npm config get registry
查看当前 registry 地址
npm config set registry https://registry.npmmirror.com
切换为淘宝镜像加速
npm config set <key> <value>
设置配置项(写入 .npmrc)
npm config list
查看所有配置
npm cache clean --force
清理 npm 缓存
npm cache verify
验证并清理缓存垃圾
npm ci
基于 lock 文件干净安装(CI/CD 推荐)

💡 Tips

  • npm install 不带参数会安装 package.json 中的所有依赖。
  • package-lock.json 锁定依赖版本,应该提交到版本控制。
  • npx 可以临时运行包而不全局安装,如 npx create-react-app my-app。
  • npm ci 比 npm install 更快更可靠,适合 CI/CD 环境,要求 lock 文件存在。
  • npm config set registry https://registry.npmmirror.com 切换国内镜像加速下载。
  • npm audit fix --force 可能引入破坏性更新,生产环境慎用。