NPM 如何发布和使用带范围(scope)的包?

前端开发 Oct 9, 2022

您知道所有 npm 包都有一个名称。如果您要给自己的包,起一个有「寓意」的名字,会发现绝大多数单词/短语已被占用,即使没有真正的内容,这真是无可奈何的事儿。如何解决这一困境呢?你可以发布带作用域/范围(scope)的包。本文就如何发布,做简单探讨。

NPM 如何发布和使用带范围(scope)的包?

如何发布带范围(scope)的包

如果要发布带范围(scope)的包,首先得拥有 scope(即:新建组织「New Organization」);而这个组织名,得满足几个条件:1,没有被使用;2,在 Github 上拥有这个 Organization。因此,大致过程如下:

  1. 在 Github 注册组织(org),比如:@vue@types@vitejs@nicelinks
  2. 注册 npm 账号,并在 npm Create a New Organization (有付费、有免费);
  3. 创建项目并做适当的配置,详情可参见: Creating and publishing private packages
  4. 完成代码编写,并测试无误后,使用 npm publish 命令进行发布;

需要说明的是,Github Org,测试了很多能够想到简单的「名字」,均已被占用。

当然,如果您已有项目,可直接将 scope 与 registry 关联:

npm login --registry=https://www.npmjs.com/ --scope=@your-scope-name

Note:Scopes have a many-to-one relationship with registries: one registry can host multiple scopes, but a scope only ever points to one registry. Once a scope is associated with a registry, any npm install for a package with that scope will request packages from that registry instead. Any npm publish for a package name that contains the scope will be published to that registry instead. —— Fromnpm scope

scope 包的必要性

除了命名的原因外,一定要 scope 包,除了 @types/[PackageName] 这种,想不到更多了;但 Definitely Typed
这种,也不一定要发布一个 scope 包(况且权限不在手,颇为麻烦);完全可以基于 npm alias 来解决,比如:

npm i @types/quickapp@npm:quickapp-interface —save-dev

备注:用这种方式,npm 版本需要大于 6.9.0(对应 node.js 为 12.0 ),否则会报如下错误:

> npm ERR! Invalid dependency type requested: alias

您可能感兴趣的文章

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.