blog
blog copied to clipboard
gitlab CI 集成 自动化发布 npm 私有库
gitlab CI 集成 自动化发布 npm 私有库
阅读时间约为三分钟
#技术笔记
前面有一个篇文章是从零开始搭vue组件库 本篇文章是它的进阶版,通过 gitlab CI 自动化发布 npm 私有库
将Node.js模块部署到npm可能是一个复杂的过程。即使对于一个简单的模块,您的部署过程可能如下所示
npm run lint
npm run build
npm test
npm version <newversion>
git push --follow-tags
npm publish
此过程仍未涵盖有关部署Node.js模块的所有问题。
您如何保证每次构建都遵循此流程? 测试是在干净的环境中进行的吗? 本地环境是否跟生产环境统一? 如何在多个Node.js版本中运行测试?
基于以上问题,我们需通过自动化尽量来规避这些问题。
在gitlab CI 中 上面的问题都可以解决
下面是一个基于构建组件库项目的示例CI配置
image: node:8 // 这只是一个示例, 这里是你的node生成版本 亦或是你想测试的node版本
# 缓存公共node模块
cache:
key: node_modules_cache
paths:
- node_modules/
before_script:
- npm install
# 定义 stages
stages:
- check
- build
- deploy
# 定义 job
check-eslint:
stage: check
script:
- echo "检查eslint"
- npm run lint
cache:
key: node_modules_cache
# 打包组件库
webapck-components:
stage: build
cache:
key: node_modules_cache
script:
- npm run build
only: //只在dev master被触发的情况下 进行一次打包测试
- dev
- master
# 更新npm包
npm-publish:
image: timbru31/node-alpine-git
cache:
key: node_modules_cache
stage: deploy
only:
- tags
script:
# 获取 git 仓库的 tag 通过tag作为npm包发布的版本号
- export GIT_TAG=$(git describe --tags)
- echo $GIT_TAG
- npm run build
- cd packages
- export NPM_ORIGIN=$(npm config get registry)
- echo "切换npm私有源"
- npm config set registry 私有库地址
- npm version $GIT_TAG
- echo '//私有库地址/:_authToken=${NPM_TOKEN}'>.npmrc
- npm publish
- echo "回退npm源"
- npm config set registry $NPM_ORIGIN
echo '//私有库地址/:_authToken=${NPM_TOKEN}'>.npmrc
解释一下这段代码的意思 将模块发布到npm。我们需要的第一件事是授权令牌,以便能够将模块发布到npm。授权令牌可以.npmrc在主目录(~/.npmrc)中的文件中找到。该文件应包含类似于的行//registry.npmjs.org/:_authToken=YOUR_API_KEY。 如果文件不存在或者您没有看到类似于上面一行的行,请使用adduser命令验证您是否已登录到npm 。
从.npmrc文件中复制授权令牌,并将其作为名为的秘密变量添加到GitLab中NPM_TOKEN。现在NPM_TOKEN将作为GitLab CI作业中的环境变量提供。这允许我们创建一个作业来将模块发布到npm存储库,而不会在.gitlab-ci.yml文件中公开令牌,任何对存储库具有读访问权限的人都可以看到该令牌。
最后
当你push 一个 tag v1.0.0到项目, gitLab CI 将运行所有任务,并且仅在所有任务通过时自动将新版本发布到npm 。 此时,我们已成功将将Node.js模块部署到npm的整个过程简化为单个命令。
参考 Continuous Deployment to npm using GitLab CI 用 GitLab CI 进行持续集成 | Scarletsky