发布于 2026-01-06 2 阅读
0

How to use: npm tags DEV's Worldwide Show and Tell Challenge Presented by Mux: Pitch Your Projects!

如何使用:npm 标签

由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!

npm 中有一个功能会影响到每npm install一个npm publishnpm 包,然而大多数 npm 用户似乎对此并不了解。

是时候聊聊npm标签了

它们是什么

让我们直接进入正题:

  1. 对于每个npm install <package>没有明确版本号的版本,都会使用一个标签来解析正确的版本号:该latest标签。

  2. 每次npm publish都会更新或创建新的标签。是的,它latest也默认使用标签。

假设繁忙的工作日刚刚开始,你向依赖项中添加了一个新的软件包:

$ npm install cowsay

由于您没有指定要安装的版本,npm 如何决定使用哪个版本呢?它使用标签latest

请看这里:

$ npm show cowsay

cowsay@1.4.0 | MIT | deps: 4 | versions: 19
cowsay is a configurable talking cow
https://github.com/piuccio/cowsay

keywords: cow, cowsay, cowthink, figlet, talking, ASCII

bin: cowsay, cowthink

(...)

dist-tags:
latest: 1.4.0

published a month ago by piuccio <piuccio@gmail.com>

请看这里dist-tags。它只显示了一个标签,即 `<tag>`latest标签。根据npm show`<tag>` 的输出,我们已经可以想象出标签的功能是什么:

标签是将一些易于理解的标识符映射到特定版本号的一种方式。

啊哈!所以当你执行 `npm install` 命令时npm install cowsay,npm 会获取包的元数据(试试看npm show cowsay --json),包括该包所有已发布标签的列表。latest标签会告诉 npm 要安装哪个版本。

那么,为什么 npm 不直接安装发布时间戳最新的版本呢?我们稍后会解释,但这里先剧透一下:

因为最新版本npm publish可能尚未发布稳定版本,而可能是用户不应该在生产环境中运行的早期测试版。

使用标签

消费

要安装软件包,但不安装标签latest

$ npm install <package>@<tag>

一个常见的例子是:

# Install the latest alpha version of React
$ npm install react@next

出版

要发布一个不应默认安装的珍贵软件包版本:

$ npm publish --tag <tag>

这样你就可以轻松地与他人分享一些不稳定的代码,以便他们可以进行测试:

$ npm publish --tag beta

或者

$ npm publish --tag testing-feature-new-dashboard

如前所述,npm publish不带--tag参数运行也会更新一个标签:该latest标签是发布和安装的默认标签。

更改标签

如果需要,您可以随时更改标签以指向其他版本。npm dist-tag为此,请使用以下子命令:

$ npm dist-tag --help
npm dist-tag add <pkg>@<version> [<tag>]
npm dist-tag rm <pkg> <tag>
npm dist-tag ls [<pkg>]

alias: dist-tags

如果您不小心发布了使用了错误标签的版本,请使用此功能来修复标签。

与 Git 标签的区别

需要注意的是,尽管 npm 标签在技术上与 git 标签非常相似,但它们在语义上有所不同。

Git 标签指向一个提交,即特定时间点的代码,通常不会改变。Git 标签本质上等同于 npm 版本号。

另一方面,npm 标签是指向某个版本的可变指针,而该版本本身又是指向特定时间点代码的不可变指针。因此,npm 标签本质上是一个元指针。

When thinking in git terms, both npm tags and npm versions could be implemented using git tags, just that the former type of tag would be considered mutable, while the version git tags would be considered immutable.

Profit $$

So how can we use that feature to our benefit in day-to-day work?

We can:

  • Share an unstable version with beta testers: npm publish --tag beta
  • Publish a use-once-and-forget version: npm publish --tag testing-new-feature

Installing that version on the other end will be just as simple:

$ npm install my-fancy-package@testing-new-feature

Release early, release often. Don't screw with your production users, though. Use npm tags.

Happy hacking!

Teaser photo by Paul Murphy on Unsplash. Shows spray tags, not npm tags.

文章来源:https://dev.to/andywer/how-to-use-npm-tags-4lla