惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

AI
AI
TaoSecurity Blog
TaoSecurity Blog
H
Heimdal Security Blog
Help Net Security
Help Net Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Microsoft Azure Blog
Microsoft Azure Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Google DeepMind News
Google DeepMind News
爱范儿
爱范儿
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
人人都是产品经理
人人都是产品经理
大猫的无限游戏
大猫的无限游戏
N
News | PayPal Newsroom
V2EX - 技术
V2EX - 技术
博客园 - 【当耐特】
D
Darknet – Hacking Tools, Hacker News & Cyber Security
S
Secure Thoughts
C
CERT Recently Published Vulnerability Notes
罗磊的独立博客
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Privacy & Cybersecurity Law Blog
有赞技术团队
有赞技术团队
S
Schneier on Security
S
SegmentFault 最新的问题
Google Online Security Blog
Google Online Security Blog
H
Hacker News: Front Page
The Last Watchdog
The Last Watchdog
Schneier on Security
Schneier on Security
PCI Perspectives
PCI Perspectives
IT之家
IT之家
Project Zero
Project Zero
博客园 - 司徒正美
P
Privacy International News Feed
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Jina AI
Jina AI
Security Latest
Security Latest
Hacker News - Newest:
Hacker News - Newest: "LLM"
腾讯CDC
C
CXSECURITY Database RSS Feed - CXSecurity.com
阮一峰的网络日志
阮一峰的网络日志
C
Check Point Blog
aimingoo的专栏
aimingoo的专栏
V
Vulnerabilities – Threatpost
W
WeLiveSecurity
NISL@THU
NISL@THU
Webroot Blog
Webroot Blog
N
Netflix TechBlog - Medium
L
Lohrmann on Cybersecurity

Fall 的笔记本 Blog

性能优化清单 npm前端包 2分钟环境搭建 客户想要的不是她们所说的(译) TypeScript声明 git功能查找
你为什么需要 husky
2025-07-24 · via Fall 的笔记本 Blog

husky(哈士奇)一种精力和破坏力都极强的生物,混乱制造者。有一位伟大的法师说过,要用魔法来打败魔法,你需要这个 husky,帮助你避免一个不留神家被拆了。

还有一个原因是,能用工具解决的问题都使用工具解决,而非额外的人力。

如果你想要找一个项目作为参考,可以查看我的 鲜果起始页 项目

前提准备

一个 js 项目 配置好 eslint 安装好 git

添加依赖

安装 husky,husky 本身只提供了执行 git 对应命令时,调取对应的钩子函数,因此需要其它工具来执行对应的检查

commitlint 用于对提交内容(commit message)进行检查

npm i @commitlint/cli @commitlint/config-conventional -D

lint-staged 用于在缓冲区执行 lint,代码检查

cz-git 自定义 git 提交工具

更新你的 package.json

{
"scripts": {
"lint-staged": "lint-staged", // 该命令用于在缓冲区执行
"commit": "czg", // 之后可以使用 npm rum commit 代替 git commit -m ''
"prepare": "husky init" // 拉去依赖后,自动执行该命令
},
"config": {
"commitizen": { // 定义 commitlint 的配置
"path": "node_modules/cz-git"
}
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [ // 对以 js,jsx,ts,tsx 后缀名的文件使用 eslint --fix
"eslint --fix"
],
"*.{md,json}": [ // 对以 md,json 后缀名的文件使用 prettier --write
"prettier --write"
]
}
}

创建 husky 文件

husky 会在 package.json 目录创建 .husky 文件,如果没有创建,可以手动创建

手动创建 .husky\commit-msg 文件,并且添加以下内容

#!/bin/sh
# . "$(dirname "$0")/_/husky.sh"

npx --no -- commitlint --edit $1

手动创建 .husky\pre-commit 文件,并且添加以下内容

#!/bin/sh
# . "$(dirname "$0")/_/husky.sh"

npm run lint-staged

echo '✅✅✅ lint pass ✅✅✅'

你可以在这些 bash 文件中自定义命令,来实现你相对应的需求

完成

到了这里,你已经完成了在项目中添加 husky 的所有步骤,并且添加提交检查以及 git 缓冲区的检查功能

之后你可以使用 npm run commit 提交变更