npm 安装私有 git 包 即 package.json中引入需要账号和密码的远程git插件
公司内部做了一个组件库,放在了gogs(gogs 是一款极易搭建的自助 Git 服务)上,但是在项目中怎么引入呢?
引入方式如下:
"devDependencies": {
"@anyi/anyi-ui": "git+http://loader:[email protected]/anyi-front/anyi-ui.git#1.2.37"
}
因为我们gogs是有账户名和密码的,所以在地址中加入了账户名和密码,上面链接中的loader:loader,代表的就是用户名和密码,前面是用户名,后面是密码。
例如:用户名是xiaohua,密码:xiaohua123,那我们就可以这样来引入git插件
"devDependencies": {
"@anyi/anyi-ui": "git+http://xiaohua:[email protected]/anyi-front/anyi-ui.git#1.2.37"
}
后面执行npm install即可。
通过上面的案例,我们大致了解了在项目如何配置远程git插件的url。
npm install <git remote url>
实际上就是直接 install 一个 URL 而已。对于一些公有仓库, npm 还是做了一些集成的,比如 github等(示例全部出自 npm 官方文档):
npm install github:mygithubuser/myproject
npm install bitbucket:mybitbucketuser/myproject
npm install gitlab:myusr/myproj#semver:^5.0
如果我们直接安装 github 上,使用网址的方式可以表示为:
npm install git+https://github.com/shiqingyun1024/vue-summary.git
看下 npm 安装 git 仓库的协议:
<protocol>://[<user>[:<password>]@]<hostname>[:<port>][:][/]<path>[#<commit-ish> | #semver:<semver>]
我们来一个一个分析:
1、
例如:
git://github.com/user/project.git#commit-ish
git+ssh://user@hostname:project.git#commit-ish
git+ssh://user@hostname/project.git#commit-ish
git+http://user@hostname/project/blah.git#commit-ish
git+https://user@hostname/project/blah.git#commit-ish
对应案例中的git+http
"devDependencies": {
"@anyi/anyi-ui": "git+http://xiaohua:[email protected]/anyi-front/anyi-ui.git#1.2.37"
}
2、[
前面是用户名,后面是密码,对应案例中的xiaohua:xiaohua123@
"devDependencies": {
"@anyi/anyi-ui": "git+http://xiaohua:[email protected]/anyi-front/anyi-ui.git#1.2.37"
}
3、
对应 案例中的 gogs.pms.anyi-tech.com/
"devDependencies": {
"@anyi/anyi-ui": "git+http://xiaohua:[email protected]/anyi-front/anyi-ui.git#1.2.37"
}
4、
对应 案例中的 anyi-front/anyi-ui.git
"devDependencies": {
"@anyi/anyi-ui": "git+http://xiaohua:[email protected]/anyi-front/anyi-ui.git#1.2.37"
}
5、[#
对应 案例中的 #1.2.37
"devDependencies": {
"@anyi/anyi-ui": "git+http://xiaohua:[email protected]/anyi-front/anyi-ui.git#1.2.37"
}
If # is provided, it will be used to clone exactly that commit. If the commit-ish has the format #semver:, can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. If neither #or #semver:is specified, then master is used.
翻译如下:
如果使用 #
即 protocol 支持 git, git+ssh, git+http, git+https, git+file,私有仓库需要用户名和密码时需要填写用户名和密码,semver 表示需要使用的版本号, 不过貌似不生效。(npm 中有个包 semver 是专门用于比较包的版本号大小)
直接写 #branch 表示需要安装的分支号。
所以在开发过程中我们可以这么写包:
npm i git+https://username:password@git.example.com/path/reposity#master
或者使用打的 tag
npm i git+https://username:password@git.example.com/path/reposity#1.0.0
可能存在的问题是:
由于新版的 npm install 在安装时会使用 package-lock.json, 有时候同一分支不会从 github 上拉取最新的,
可能需要手动再安装一下(拿自己的仓库试了下,果然不会更新),所以安装时尽量以 tag 为标签进行安装,这样确保代码是正确的
此外,由于私有仓库都是需要密码的,这个时候需要提供一个公共账号和密码,某种程度上不利于管理吧
参考:从码云上通过git安装私有npm包
npm 安装私有 git 包