前端工程化之提交規範

實現原理前端

前端工程化之提交規範,主要是經過husky在.git目錄中埋點hooks腳本,在提交前,經過lint-staged對當前修改作相應的格式化/校驗,在提交時,經過commitlint對提交信息作校驗,或經過commitizen模板生成規範的提交信息,若是須要版本日誌,能夠經過changelog生成修改日誌。
1. 準備
git項目根目錄下若沒有package.json,初始化生成:
$ npm init -y
2. husky鉤子
husky是一個爲git客戶端增長hook的工具,經過在.git目錄下增長相應的鉤子實如今pre-commit 階段執行一系列流程,依賴安裝:
$ npm i husky -D
package.json中添加"husky": {}字段,或新建文件.huskyrc,配置以下:
{
    "hooks": {
        "pre-commit": "lint-staged",
        "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
}
上面示例中配置了pre-commit、commit-msg兩個hooks
3. lint-staged過濾
Lint-staged僅對git暫存區(本次修改的)文件執行指定動做,如:格式美化、校驗、git add等,依賴安裝:
$ npm i lint-staged prettier -D
package.json中添加"lint-staged": {}字段,或新建.lintstagedrc文件,配置以下:
{
    "*.{js,jsx,ts,tsx}": [
        "prettier --single-quote --write",
        "git add"
    ]
}
若是安裝使用eslint,能夠把prettier項換成"eslint --quiet --fix",
4. commitlint校驗
commitlint用於commit提交信息的規範校驗,依賴安裝:
$ npm i @commitlint/config-conventional @commitlint/cli -D
commit格式化校驗配置文件,新建./commitlint.config.js文件,配置以下:
module.exports = {
    extends: ['@commitlint/config-conventional'],
    rules: {
        'type-enum': [
            2,
            'always',
            [
                'build', // 構建系統/工具更改
                'ci', // 持續集成配置/腳本更改
                'chore', // 構建過程或輔助工具的變更
                'docs', // 文檔更改
                'feat', // 新功能、特性
                'fix', // bug修復
                'merge', // Merge branch
                'perf', // 性能優化
                'refactor', // 代碼重構
                'revert', // 代碼回滾
                'style', // 代碼風格(不影響代碼運行的變更)
                'test' // 測試用例
            ]
        ]
    }
}
提交時格式:git ci -am '<type>: <subject>'
5. commitizen模板
commitizen提供了交互式的模板,根據提示自動生成符合規範的commit message,依賴安裝:
$ npm i commitizen -D
package.json script項添加配置:
"scripts": {
        "commit": "git add . && git-cz",
    },
    "config": {
        "commitizen": {
          "path": "./node_modules/cz-conventional-changelog"
        }
    }
提交時:npm run commit,根據提示生成規範提交信息, 注意:若是當前爲git項目子目錄,config字段中path路徑需修改
6. changelog版本日誌
用於自動生成版本日誌 CHANGELOG.md 文件,依賴安裝:
$ npm i standard-changelog -D
package.json script項添加配置:
"scripts": {
        "log": "standard-changelog -f && git add CHANGELOG.md"
    }
生成日誌時,直接運行:npm run log
相關文章
相關標籤/搜索