我如何 运行 只在我想提交的文件上更漂亮?

How Do I Run Prettier Only on Files That I Want to Commit?

在每次提交前使用 Husky, I've set up my package.json with a precommit hook so that my JavaScript code is formatted using Prettier

{
  "name": "prettier-demo",
  "scripts": {
    "precommit": "prettier --write **/*.js && git add ."
  },
  "devDependencies": {
    "husky": "^0.14.3",
    "prettier": "^1.8.2"
  }
}

这很好用,但有两个缺点:

  1. 如果我有一个包含数千个 JavaScript 文件的大型项目,我必须等待 Prettier 处理所有文件,即使只有少数文件发生变化;这可能会花费很长时间,并且在每次提交完成后都会很快让我感到紧张

  2. 有时我只想暂存几个文件用于提交,将其他更改排除在提交之外;因为我在 运行ning Prettier 之后做了一个 git add .,所以我所有的更改总是会在 commit

  3. 中结束

如何在每次提交前 运行 Prettier 仅对已暂存的文件,忽略未暂存或未更改的文件?

您可以使用 lint-staged:

Linting makes more sense when running before committing your code. By doing that you can ensure no errors are going into repository and enforce code style. But running a lint process on a whole project is slow and linting results can be irrelevant. Ultimately you only want to lint files that will be committed.

This project contains a script that will run arbitrary npm and shell tasks with a list of staged files as an argument, filtered by a specified glob pattern.

使用以下命令安装 lint-stagedhusky,这是预提交挂钩所必需的:

npm install --save-dev lint-staged husky

按如下方式更改您的 package.json:

{
  "scripts": {
    "precommit": "lint-staged"
  },
  "lint-staged": {
    "*.js": [
      "prettier --write",
      "git add"
    ]
  }
}

如果您不想添加 devDependency lint-staged,您也可以使用 Bash 脚本执行相同的操作:

#!/usr/bin/env bash
# chmod +x this and save in your PATH. Assumes `prettier` is in your `devDependencies` already
BASE=$(git merge-base master HEAD) # change master to whatever your trunk branch is
FILES=$(git diff --name-only $BASE HEAD | xargs)

npx prettier --list-different $FILES

# Want eslint too?
# npx eslint --ignore-path=.prettierignore $FILES

我发现 运行:

prettier --write $(git diff --name-only --diff-filter d | grep '\.js$' | xargs)

足以满足我的需要,只是创建了一个别名并使用了它。

我用这个包pretty-quick

在我的 package.json

添加脚本
"pretty-quick": "pretty-quick" 

scripts {}

之下

然后在我的pre-commit钩子下.husky/pre-commit

我加

npm run pretty-quick

prettier 文档对此有 section

我用pretty-quick

npx husky-init
npm install --save-dev pretty-quick
npx husky set .husky/pre-commit "npx pretty-quick --staged"