0


【前端】husky 的使用

husky 是一个优化 git hooks 的 npm 库

Modern native Git hooks made easy

安装和使用

1.安装

npm install husky --save-dev
  1. 初始化
    npx husky install
    
    ;官方文档的写法是在 package.json 中初始化,本质上还是执行了 npx husky install 指令
  2. 添加 hook:
    npx husky add .husky/pre-commit "npm test"
    
    ,这段代码会在执行 commit 前运行 npm test

需求

目前的需求并不是在提交前运行某个脚本,而是在提交信息前增加一个前缀,比如

git commit -m "chore: init"

,最终得到的 message 为

"[xxx] chore:init"

,为此需要创建一个

prepare-commit-msg

文件:

npx husky add .husky/prepare-commit-msg

。注意这段指令并没有指定执行该 hook 时执行的指令,结果会导致

.husky/prepare-commit-msg

中会有行

undefined

,使 commit 时执行脚本报错:

command undefined not found

解决方式:

vim .husky/prepare-commit-msg
# 删掉 undefined 行,并添加如下代码:#!/usr/bin/env sh."$(dirname -- "$0")/_/husky.sh"commit_msg_file=$1prepend_msg="[xxx]"# 检查提交消息是否以 [xxx] 前缀开头if!grep-q"$prepend_msg""$commit_msg_file";thenecho"${prepend_msg}`(cat $commit_msg_file)`">"$commit_msg_file"fi

总结

本文记录了 husky 的基本使用方式和踩到的坑,但本质上需要了解的是:

  1. git hooks
  2. Linux 命令行

好在目前 LLM 非常发达,碰到类似的问题可以直接问 AI。

标签: 前端

本文转载自: https://blog.csdn.net/qq_39559879/article/details/132272484
版权归原作者 缓次郎 所有, 如有侵权,请联系我们删除。

“【前端】husky 的使用”的评论:

还没有评论