LoginSignup
8
0

More than 3 years have passed since last update.

eslintの特定のルールはwarnに留めておきたいが、引っかかるコードをコミットさせたくない場合

Last updated at Posted at 2020-03-16

前提

husky, lint-stagedでコミット前にeslintしている

経緯

eslintのerrorで指定してあった或るルールをwarnに変えるコミットがあり、
「そもそも error は動作しなくなったり特に危険であるものに使われるべきで、よほどのことがない限り使うべきではない」という意見があった
確かに、と思ったがコミットもさせたくなくて、方法を調べた

結論

eslintのruleはwarn指定しつつ、
https://eslint.org/docs/user-guide/command-line-interface#max-warnings
のオプションを用いて --max-warnings=0 をlint-stagedに追加


module.exports = {
  '**/*.ts?(x)': ['eslint --max-warnings=0 --fix', 'prettier --write'],
};

これでwarnも引っかかるとエラー終了してコミットできなくなる

✖ 1 problem (0 errors, 1 warning)

ESLint found too many warnings (maximum: 0).

これで、普段はwarnに引っかかるコードは生まれず、 --no-verify などをつけた暫定的なコミットなどで意図してwarnに引っかかるコードがコミットされたとき、CIによるeslintは通る想定になる

追記

--max-warning をつけると、 .eslintignore に書いたファイルがlint-staged のときだけ以下のようなwarnを吐いてコミットできなくなった

0:0 warning File ignored because of a matching ignore pattern. Use "--no-ignore" to override

eslintの--no-error-on-unmatched-pattern オプションを付けても解決しなかった
解決策としては、 https://github.com/okonet/lint-staged#how-can-i-ignore-files-from-eslintignore- に従って以下のような設定にすると直った

const { CLIEngine } = require('eslint');
const cli = new CLIEngine({});

module.exports = {
  // @see https://github.com/okonet/lint-staged#how-can-i-ignore-files-from-eslintignore-
  '**/*.ts?(x)': [files => 'eslint --max-warnings=0 --fix ' + files.filter(file => !cli.isPathIgnored(file)).join(' '), 'prettier --write'],
};

8
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
0