首页 > web前端 > js教程 > 正文

Husky 和 ​​lint-staged:保持代码一致性

WBOY
发布: 2024-07-20 10:23:38
原创
378 人浏览过

When a team works on a software project together, it's important for everyone's code to be neat and easy to understand. But sometimes, different computers and ways of working can make the code messy. Tools like husky and lint-staged can help fix this problem by checking the code automatically before it's added to the project.


What is lint-staged?

lint-staged is a tool that checks your code for mistakes and fixes them when it's staged in git. By using lint-staged, it helps keep your code clean and consistent.

Installation

1 . Install lint-staged as a development dependency:

npm install --save-dev lint-staged
登录后复制

2 . Configure lint-staged in your package.json file to run eslint and prettier on js and ts files.

"lint-staged": {
  "*.{js,jsx,ts,tsx}": [
    "eslint --fix --max-warnings=0", // both errors and warnings must be fixed
    // "eslint --fix" // errors must be fixed but warnings can be ignored
    "prettier --write"
  ]
}
登录后复制

3 . Run lint-staged on staged files using the following command:

npx lint-staged
登录后复制

What is husky?

husky is a tool that manages git hooks, automatically running scripts before each git commit. This setup ensures that lint-staged checks your code before it's committed. It helps you maintain code quality by catching issues before they're finalized.

Installation

1 . Install husky and initialize it:

# husky init (create .husky folder)
npx husky-init && npm install

# husky - Git hooks install
npx husky install
登录后复制

2 . Check if prepare command is added in your package.json

"scripts": {
    "prepare": "husky install"
},
登录后复制

3 . Edit .husky > pre-commit file with the following to run lint-staged before each commit

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

npx lint-staged
登录后复制

How It Works

  1. Stage your code changes.
  2. husky triggers the pre-commit hook.
  3. The pre-commit hook executes lint-staged.
  4. lint-staged runs eslint and prettier checks on staged files.
  5. If errors or warnings are found, the commit is prevented with an error message.

Husky and lint-staged: Keeping Code Consistent


以上是Husky 和 ​​lint-staged:保持代码一致性的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!