Scoped Packages 域级包介绍
在 npm 的包管理系统中,存在一种 scoped packages 机制,是将一些 packages 以 @scope/package
的命名形式集中在一个命名空间下面,实现域级的包管理。
如: @babel/core
、@babel/preset-env
、@babel/runtime-corejs3
等 package 的存在形态。
域级包发布过程
1. 准备好npm账户、密码、邮箱
用于发布时登录npm账户
发布域级包需要在NPM账户上创建对应的Organizations,也就是命名空间@scope,创建的时候不需要带@
2. 初始化项目并关联git远程仓库
初始化项目指令:
npm init -y
调整package.json数据。【包名、入口文件、作者、描述、git仓库地址】
{
"name": "@scope/test11",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"repository": {
"type": "git",
"url": "https://github.com/xxxxx/xxxx.git"
},
"author": "xxx",
"license": "ISC"
}
上传到远程仓库
git init
git add .
git commit -m "first commit"
git branch -M main // ***分支重命名
git remote add origin https://github.com/xxxxx/xxxx.git
git push
3. 登录NPM账户
设置npmg官方镜像: 【如果是不需要】
npm config get registry
npm config set registry registry.npmjs.org/
登录个人NPM账户:
npm login
----
Username: xxx
Password:
Email: (this IS public) xx@xx.com
npm notice Please check your email for a one-time password (OTP)
Enter one-time password: xxxx
Logged in as xxx on https://registry.npmjs.org/.
检验登录指令:
npm whoami
4. 执行发布
npm publish
5. 线上查看验证
发布过程中遇到Error合集
1. 403 Forbidden
提示无权限,npm的包名在NPM上重复,需要换一个名字
npm ERR! code E403
npm ERR! 403 403 Forbidden - PUT https://registry.npmjs.org/xxxx - You do not have permission to publish "xxxx". Are you logged in as the correct user?
npm ERR! 403 In most cases, you or one of your dependencies are requesting
npm ERR! 403 a package version that is forbidden by your security policy, or
npm ERR! 403 on a server you do not have access to.
2. 402 发布私有包需要付费
发布域级包时才会出现,原因是当包名以@scope开头时,npm publish会默认发布为私有包,但是 npm 的私有包需要付费
npm ERR! code E402
npm ERR! 402 Payment Required - PUT https://registry.npmjs.org/@xx%2fxx - You must sign up for private packages
所以,需要添加如下参数进行发布:
npm publish --access public
或者 在package.json中添加配置:
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
}
3. 404 找不到对应地址
发布域级包时会出现,要使用名称 @scope/package
在 NPM 上发布包,则需要确保 @scope
命名空间在 NPM 上存在。
npm ERR! code E404
npm ERR! 404 Not Found - PUT https://registry.npmjs.org/@xxx%2fxxx - Not found
npm ERR! 404
npm ERR! 404 '@xxx/xxx@1.0.0' is not in this registry.
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.
需要创建该命名空间,需要使用 @scope
名称在 NPM 上创建组织Organizations: