> For the complete documentation index, see [llms.txt](https://lizh.gitbook.io/knowledge/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lizh.gitbook.io/knowledge/nodejs-xi-lie/05npm-chang-yong-ming-ling.md).

# NPM：常用命令

npm（Node Package Manager）随 Node.js 一起安装，用来装包、改依赖、查帮助、发 registry。命令很多，日常真正反复敲的只有几类；别名和默认行为记准，比把 `npm -l` 整页背下来有用。

不确定某条命令时，先 `npm <command> -h`。

## 帮助与版本

```shell
npm -h                 # 总帮助
npm <command> -h       # 单条命令的帮助
npm help <term>        # 打开该主题的手册页
npm -l                 # 列出全部命令（很长）

npm -v                 # 只打印 npm 自己的版本
npm --version          # 同上
```

查看运行时各组件版本：

```shell
npm --versions
node -p "process.versions"
```

`npm --versions` 会带上当前目录 `package.json` 的包版本（若有）以及 Node 的 `process.versions`。

```json
{
  "npm": "10.9.2",
  "node": "22.14.0",
  "v8": "12.4.254.21-node.22",
  "uv": "1.49.2",
  "zlib": "1.3.1",
  "brotli": "1.1.0",
  "ares": "1.34.4",
  "modules": "127",
  "nghttp2": "1.64.0",
  "napi": "9",
  "llhttp": "9.2.1",
  "openssl": "3.0.15",
  "cldr": "46.0",
  "icu": "76.1",
  "tz": "2025a",
  "unicode": "16.0"
}
```

## 初始化与配置

```shell
npm init               # 问答式生成 package.json
npm init -y            # 全部用默认值（也写作 --yes）

npm config set <key> <value>
npm config get <key>
npm config delete <key>
npm config list        # 列出生效配置（含默认值时加 -l）
```

配置分层：项目 `.npmrc`、用户 `~/.npmrc`、全局。`npm config set` 默认写用户级。

常见键：`registry`、`cache`、`prefix`、`engine-strict`。

## 安装、更新、卸载

```shell
npm install                          # 按 package.json 和 lockfile 装齐依赖
npm i                                # install 的别名
npm ci                               # 严格按 lockfile 全新安装，适合 CI；不改 lockfile

npm install [-g] <pkg>[@<version>]   # 装指定包；-g 全局
npm install <pkg> <pkg>              # 一次装多个
npm install <pkg> --save             # 写入 dependencies（npm 5 起已是默认，可省略）
npm install <pkg> -S                 # 同上
npm install <pkg> --save-dev         # 写入 devDependencies
npm install <pkg> -D                 # 同上
npm install <pkg> --no-save          # 只装进 node_modules，不改 package.json
npm install --omit=dev               # 不装开发依赖（旧旗标 --production 仍可用）

npm uninstall [-g] <pkg>             # 卸载；别名 rm、un、unlink、remove
npm update <pkg>                     # 在 package.json 的 semver 范围内更新
npm update -g <pkg>                  # 更新全局包
npm outdated                         # 列出可更新的包（当前、想要、最新）
```

全局安装位置用 `npm root -g` 查看，随 Node 版本、nvm 前缀变化。

## 查看依赖与包信息

```shell
npm root                 # 当前项目 node_modules 路径
npm root -g              # 全局 node_modules 路径

npm ls                   # 当前项目直接依赖（树状）
npm ls --all             # 整棵依赖树
npm ls <pkg>             # 某个包出现在树的哪些位置
npm ls -g                # 全局包
npm explain <pkg>        # 为什么会装到这个包（别名 why）

npm search <pkg>         # 在 registry 里搜
npm view <pkg>           # 看 registry 上的包元数据
npm view <pkg> version
npm view <pkg> versions
```

`npm view`、`npm info`、`npm show`、`npm v` 是同一条命令的别名，不必记四套。

## 脚本与一次性命令

```shell
npm run <script>         # 跑 package.json 里 scripts 的命令
npm start                # 不必写 run 的内置脚本
npm test                 # 同上
npm exec -- <cmd>        # 跑本地 .bin 或临时安装后执行
npx <cmd>                # npm 7 起即 npm exec
npm pack                 # 按发布规则打 tarball
npm pack --dry-run       # 只列出将打进包的文件
npm audit                # 查已知漏洞
npm audit fix            # 在 semver 范围内自动修
```

## 源与缓存

```shell
npm config get registry
npm config set registry https://registry.npmjs.org
npm config set registry https://registry.npmmirror.com

npm cache clean --force
npm cache verify
```

国内镜像现行域名是 **npmmirror**（`https://registry.npmmirror.com`）。旧的 `npm.taobao.org` 已停。

用 nrm 在多个源之间切换：

```shell
npm install -g nrm --registry=https://registry.npmmirror.com
nrm ls
nrm use taobao
nrm use npm
```

较新的 nrm 里 `taobao` 已指向 npmmirror。若 `nrm ls` 仍是 `registry.npm.taobao.org`，升级 nrm 或手动改别名。

`cnpm` 是另一套客户端，不是改源后的 npm。仍可用，但和官方 npm 的 lockfile、脚本行为不完全相同；只改 registry 通常就够。

```shell
npm install -g cnpm --registry=https://registry.npmmirror.com
cnpm install <pkg>[@<version>]
```

## 登录与发布

```shell
npm login
npm whoami
npm publish
npm publish --access public          # 范围包要公开时
npm unpublish <name>[@<version>]
```

发布必须对着官方源 `https://registry.npmjs.org`。镜像源上 `publish` 会报无权限。撤销发布有 72 小时等限制。

## npm version

在包目录执行，按 SemVer 改 `package.json`（以及 lockfile）。若在 git 仓库且工作区干净，默认还会提交并打 tag。别名是故意拼错的 `verison`。

```shell
npm version [<newversion> | major | minor | patch | premajor | preminor | prepatch | prerelease | from-git]
```

不带参数时，现行 CLI 打印 **当前包** 的版本，不会弹出上面那份 Node 组件对照表。

| 命令                       | 作用                            | 示例                                        |
| ------------------------ | ----------------------------- | ----------------------------------------- |
| `npm version prerelease` | 预发布号 +1；还没有预发布段时先落到下一修订的 `-0` | `1.0.0` → `1.0.1-0`；`1.0.1-0` → `1.0.1-1` |
| `npm version prepatch`   | 修订号 +1，预发布为 `0`               | `1.0.1-1` → `1.0.2-0`                     |
| `npm version preminor`   | 次版本 +1，修订和预发布为 `0`            | `1.0.2-0` → `1.1.0-0`                     |
| `npm version premajor`   | 主版本 +1，其余为 `0`                | `1.1.0-0` → `2.0.0-0`                     |
| `npm version patch`      | 去掉预发布号变成正式版；已是正式版则修订 +1       | `2.0.0-0` → `2.0.0`；`2.0.0` → `2.0.1`     |
| `npm version minor`      | 去掉预发布或升次版本，修订置 `0`            | `2.0.1` → `2.1.0`                         |
| `npm version major`      | 去掉预发布或升主版本，其余置 `0`            | `3.1.0` → `4.0.0`                         |

也可以直接写死新版本：`npm version 2.3.4`。`from-git` 用最新 git tag 当新版本。

常用参数：

* `allow-same-version`：布尔，默认 `false`。允许新版本和当前相同。
* `commit-hooks`：布尔，默认 `true`。提交时跑 git commit 钩子。
* `git-tag-version`：布尔，默认 `true`。自动 `git tag`。不打 tag 用 `--no-git-tag-version`。
* `preid`：字符串，默认空。预发布前缀，例如 `--preid=alpha` 得到 `1.2.0-alpha.0`。

有 git 时顺序是：检查工作区 → `preversion` 脚本 → 改版本号 → `version` 脚本 → commit、tag → `postversion` 脚本。
