返回介绍

Pre-commit Hook

发布于 2019-12-07 19:27:48 字数 4255 浏览 1047 评论 0 收藏 0

You can use Prettier with a pre-commit tool. This can re-format your files that are marked as "staged" via git add before you commit.

Option 1. lint-staged

Use Case: Useful for when you want to use other code quality tools along with Prettier (e.g. ESLint, Stylelint, etc.) or if you need support for partially staged files (git add --patch).

Make sure Prettier is installed and is in your devDependencies before you proceed.

npx mrm lint-staged

This will install husky and lint-staged, then add a configuration to the project's package.json that will automatically format supported files in a pre-commit hook.

See https://github.com/okonet/lint-staged#configuration for more details about how you can configure lint-staged.

Option 2. pretty-quick

Use Case: Great for when you want an entire file formatting on your changed/staged files.

Install it along with husky:

yarn add pretty-quick husky --dev

and add this config to your package.json:

{
  "husky": {
    "hooks": {
      "pre-commit": "pretty-quick --staged"
    }
  }
}

Find more info from here.

Option 3. pre-commit

Use Case: Great when working with multi-language projects.

Copy the following config into your .pre-commit-config.yaml file:

- repo: https://github.com/prettier/prettier
  rev: "" # Use the sha or tag you want to point at
  hooks:
    - id: prettier

Find more info from here.

Option 4. precise-commits

Use Case: Great for when you want partial file formatting on your changed/staged files.

Install it along with husky:

yarn add precise-commits husky --dev

and add this config to your package.json:

{
  "husky": {
    "hooks": {
      "pre-commit": "precise-commits"
    }
  }
}

Note: This is currently the only tool that will format only staged lines rather than the entire file. See more information here

Read more about this tool here.

Option 5. bash script

Alternately you can save this script as .git/hooks/pre-commit and give it execute permission:

#!/bin/sh
FILES=$(git diff --cached --name-only --diff-filter=ACMR "*.js" "*.jsx" | sed 's| |\\ |g')
[ -z "$FILES" ] && exit 0

# Prettify all selected files
echo "$FILES" | xargs ./node_modules/.bin/prettier --write

# Add back the modified/prettified files to staging
echo "$FILES" | xargs git add

exit 0

If git is reporting that your prettified files are still modified after committing, you may need to add a post-commit script to update git's index as described in this issue.

Add something like the following to .git/hooks/post-commit:

#!/bin/sh
git update-index -g

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文