14

我正在尝试使用预提交挂钩在提交发生之前检测 eslint 错误。我正在使用 husky 和 ​​lint-staged。但它对 src 中的所有文件运行 lint 命令,而不是仅对暂存文件运行。这是我的 package.json 文件。

"scripts": {
    "test:ci": "cross-env CI=true react-scripts test --bail --passWithNoTests",
    "lint": "eslint src/**/*.{js,jsx}",
    "lint:fix": "eslint . --fix",
    "precommit": "npm run lint && npm run test:ci"
  }
"husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
"lint-staged": {
    "*.js": [
      "npm run precommit"
    ],
    "*.jsx": [
      "npm run precommit"
    ]
  }

有什么办法让它只适用于暂存文件而不适用于目录中存在的其他文件?

4

4 回答 4

0

使用 ESLint CLI 你有一个帮助参数npx eslint -h, --help,或者你可以在官方 ESLint 文档页面/CLI上查看 CLI 文档。有一节与缓存相关,因此 ESLint 只查看已更改的文件。

Caching:
  --cache                         Only check changed files - default: false
  --cache-file path::String       Path to the cache file. Deprecated: use --cache-location - default: .eslintcache
  --cache-location path::String   Path to the cache file or directory
  --cache-strategy String         Strategy to use for detecting changed files in the cache - either: metadata or content - default: metadata
于 2022-01-30T16:12:09.587 回答
0

根据这个lint-staged 示例,我实现了为了仅对暂存文件进行 lint(大约需要 5 秒),除非有超过 5 个暂存文件,它会检查所有 repo(可能需要超过 1 分钟):

  1. 升级lint-staged包到最新版本
  2. .lintstagedrc.js在 repo 的根目录中添加一个文件。它可能包含如下内容:
module.exports = {
  '**/*.js?(x)': (filenames) =>
    filenames.length > 5 ? 'eslint --ext .js,.jsx . --ignore-path .gitignore --fix .' : `eslint ${filenames.join(' ')} --fix`,
  "*.json": [
    "prettier --write"
  ]
}
  1. package.json从文件中删除旧的“lint-staged”命令
于 2021-07-08T09:52:55.703 回答
0

使用 husky v7/lint-staged v11.2.0 - 暂存文件将简单地添加到命令的末尾,以空格分隔。如果你有一个.husky/pre-commit调用 的文件npx lint-staged,那么你有一个 lint-staged 配置,如下所示:

{
  '*.js': [
    'eslint'
  ]
}

而你修改 src/foo.js 和 src/bar.js,将会运行的命令是:

eslint src/foo.js src/bar.js

在 lint-staged 配置中使用什么命令并不重要。文件只是添加到命令的末尾,用空格分隔。

于 2021-10-06T19:17:55.113 回答
0
"husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    },
},
"lint-staged": {
    "*.js": [
        "eslint src/**/*.{js}",
        "cross-env CI=true react-scripts test --bail --passWithNoTests",
        "git add"
    ]
},
于 2020-06-17T09:25:29.233 回答