husky+lint-staged 在 unstaged 文件上运行

Haj*_*aji 6 githooks node.js reactjs eslint

我正在尝试添加一个预提交的 git 钩子,它只会在接触(暂存)文件上运行我的 linter。我的项目基于 Create React App。

我将以下内容添加到我的package.json

  "scripts": {
    "lint": "eslint 'src/**/*.js'",
    "lintfix": "eslint 'src/**/*.js' --fix"
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*": ["npm run lintfix --", "git add"]
  }
Run Code Online (Sandbox Code Playgroud)

我运行它的原因"*"是因为我希望脚本本身 (lintfix) 强制执行它的配置 ( src/**/*.js)。

问题是我在整个代码库中遇到了大量 eslint 错误,而不仅仅是在我希望的暂存文件上。

仅在暂存文件上运行 eslint 需要什么配置?

seb*_*ier 6

从 lint-staged readme.md

{ "*": "your-cmd" }
Run Code Online (Sandbox Code Playgroud)

此配置将your-cmd使用作为参数传递的当前暂存文件列表执行。

因此,考虑到您执行了 git add file1.ext file2.ext,lint-staged 将运行以下命令:

your-cmd file1.ext file2.ext

因此,查看您的 package.json,您正在运行以下内容:

eslint 'src/**/*.js' --fix file1.js file2.js file3.js fileX.js... ....
Run Code Online (Sandbox Code Playgroud)

您需要替换npm run lintfix --eslint --fix先行先试,如果它的工作原理(应该),那么调整你lintfix不一般的命令src/**/*.js正则表达式。