自动化构建组件

自动化构建组件

一个组件的从开发到发布的过程,一般是开发-改版本-编译-发布,其中,只有开发是需要脑力劳动的,改版本、编译和发布则是机械操作。那么,是否有工具可以把我们从重复的劳动中解放出来呢?已经有人想到了这一点,并推出了semantic-release

semantic-release

semantic-release automates the whole package release workflow including: determining the next version number, generating the release notes and publishing the package.

也就是说,semantic-release可以承包开发之外的一系列流程。

其中,determining the next version number引起了我的注意。众所周知,版本号分为三位major.minor.patch,手动修改版本号时,我都要想一下要改minor还是patch,一个工具又如何修改呢?
答案是根据git提交时的commit message

举个🌰,你在commit message中写道:fix: fix TypeError,那么,这个时候就应该增加patch位;如果你写的是feat: add auto fix feature,那么就应该加minor位。

由此,我们可以知道,commit message应该有几种不同的类型,semantic-release可以从提交记录中,分析这些类型,并计算得到版本号。

那么,commit message有哪些类型呢?又是否有工具可以进行规范呢?

commitizen

此处,我们以 Angular Commit Message Conventions为例,共8种类型。

为了规范,我们引入commitizen作为管理工具。安装配置后,每次git commit操作,都执行命令npm run commit,此时可以依次选择typescope等,来生成一个完整的commit message

travis

接下来,我们选择travis作为CI,这样,我们要做的就只有git commit+git push,剩下的一切就都交给工具了。

travis只支持GitHub项目托管,如果用GitLab等,可以选择其他的CI。

首先正确配置GitHub和npm的权限,然后在项目根目录下增加travis配置文件.travis.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
language: node_js
cache:
directories:
- ~/.npm
notifications:
email: false
node_js:
- '10'
- '11'
- '8'
script:
- npm run test:prod && npm run build
after_success:
- if [ "$TRAVIS_BRANCH" = "master" -a "$TRAVIS_PULL_REQUEST" = "false" ]; then npm run travis-deploy-once "npm run semantic-release"; fi
branches:
except:
- /^v\d+\.\d+\.\d+$/

最后,我们再回头,把semantic-relaese的配置文件.releaserc补上:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"branch": "master",
"plugins": [
"@semantic-release/commit-analyzer",
[
"@semantic-release/npm",
{
"tarballDir": "dist"
}
],
[
"@semantic-release/github",
{
"assets": "dist/*.tgz"
}
],
]
}

本文对于详细的semiotic-release和travis配置并没有涉及,因为这些在官方文档中都有详细的描述。

OK,大功告成,你也可以根据你的需求,修改.releaserc文件,比如生成changelog、修改根据commit message修改版本号的策略等。

构建成功的话,你就可以在你的npm下发现你的npm包了~