npm install -D husky @commitlint/config-conventional @commitlint/cli
npm install -D commitizen cz-conventional-changelog
npm install -D semantic-release @semantic-release/git @semantic-release/changelog @semantic-release/npm
husky
npx husky init
即可(v9):
.husky/
中创建 pre-commit
脚本,并更新 package.json
中的 prepare
脚本echo "pnpm run lint-staged" >> .husky/pre-commit
(不要使用echo >
,会覆盖文件)commitlint
校验commit信息(避免有人不用配置好的命令)
创建 commitlint.config.cjs
并写入:
module.exports = {
extends: ["@commitlint/config-conventional"]
};
添加钩子echo 'npx --no-install commitlint --edit "$1"' >> .husky/commit-msg
(commit-msg
也是一个git hook,作用在git commit
之后,但 commit
还未完成时)
commitizen
在 package.json
中添加 config.commitizen
配置:
{
"config": {
"commitizen": {
"path": "cz-conventional-changelog"
}
}
}
此时运行pnpm cz
即有交互式界面,如果想更简化,可以在package.json的scripts
中添加"commit": "git add . && pnpm cz && git push origin main"
semantic-release
:新建release.config.cjs
文件,写入:
module.exports = {
branches: ["main"], // 仅在 main 分支发布
repositoryUrl: "[email protected]:osmanthuspeace/osp-cli.git", // 强制使用 SSH(如果不允许https链接的话)
plugins: [
"@semantic-release/commit-analyzer", // 分析 commit 记录,确定版本号(major/minor/patch)
"@semantic-release/release-notes-generator", // 生成 release notes
"@semantic-release/changelog", // 更新 CHANGELOG.md
["@semantic-release/npm", {
"npmPublish": true, // 修改 package.json 版本,并发布到 npm
}],
["@semantic-release/git", {
"assets": ["package.json", "CHANGELOG.md"], // 自动更新的文件
"message": "chore(release): ${nextRelease.version} [skip ci]\\n\\n${nextRelease.notes}"
}]
]
};
commit信息为feat!
会触发major改变,feat
触发minor,fix
触发patch
在 .github/workflow**s**/release.yml
中写入(注意注释):
name: Release
on:
push:
branches:
- main
jobs:
release:
runs-on: ubuntu-latest
permissions:
contents: write
issues: write
pull-requests: write
id-token: write # <https://github.com/semantic-release/npm/blob/master/README.md#npm-provenance-on-github-actions>
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0 # 重要:必须获取完整的 Git 历史
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: "latest" # 需要20+
registry-url: "<https://registry.npmjs.org/>"
- name: Set up pnpm
uses: pnpm/action-setup@v2 # 使用官方的 pnpm action
with:
version: 8
- name: Install dependencies
run: pnpm install
- name: Run Semantic Release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # 无需手动设置,GitHub 会自动注入
NPM_TOKEN: ${{ secrets.NPM_TOKEN }} # 手动设置,使用Automation类型的Token
run: npx semantic-release
NPM_TOKEN
在npm个人页面→Access Tokens→Generate New Token→Classic Token→Automation获取,并放在github上Settings→Secrets and variables→Actions→Repository secret中
npm test
命令会抛错,可以先用"test": "echo \\"No tests yet\\"",
代替