禁止するコード
function func(num) {
return num === 0;
}
if (func) //付け忘れ
console.log("zero");
class A {
func(num) {
return num === 0;
}
method() {
if (this.func) //付け忘れ
console.log("zero");
}
}
条件文の判定部分に関数を使い、()を付け忘れている。
条件文の判定部分に()を付けない関数を使うことを禁止するESLintのカスタムルールを作成する。
正しいコード
function func(num) {
return num === 0;
}
if (func()) //()を追加
console.log("zero");
class A {
func(num) {
return num === 0;
}
method() {
if (this.func()) //()を追加
console.log("zero");
}
}
ESLintのカスタムルール
no-cond-funcを作った。
--fix(自動修正)にも対応した。
動作確認
> eslint test.js
7:1 error evaluate function as condition rulesdir/no-cond-func
20:9 error evaluate method as condition rulesdir/no-cond-func
eslint-plugin-rulesdirを使っているので、コマンドラインオプションに--rulesdir rulesがない。
PoC
以前の記事でin+配列を禁止するカスタムルールがESLintに追加されたら嬉しいと望んだ。
しかし、ESLintのガイドを読んだら
As of 2020, we only accept rules related to new ECMAScript features. We prefer that new rules be implemented in plugins.
新しいECMAScriptの特徴に関するルールだけを受け入れる。
Keep in mind that we have over 200 rules, and that is daunting both for end users and the ESLint team (who has to maintain them). As such, any new rules must be deemed of high importance to be considered for inclusion in ESLint
200以上のルールがあってエンドユーザーと(それらを維持しなければならない)ESLintチームをひるませる。
ESLintに入る新しいルールは超重要なものでなければならない。
Implementation is Your Responsibility
The ESLint team doesn't implement new rules that are suggested by users because we have a limited number of people and need to focus on the overall roadmap.
Once a rule is accepted, you are responsible for implementing and documenting the rule.
ESLintチームは限られた人員しかいないので、ユーザーが提案した新しいルールを実装しない。
ユーザーにルールの実装と文書化の責任がある。
とあった。
ESLintチームの状況はこのようになっている。
新しいルールは、新しいECMAScriptの特徴に関係する超重要なものでないならプラグインで作り、npm パッケージを作って公開することになる。
関連記事
New Rules - ESLint - Pluggable JavaScript linter
おわりに
もしno-in-arrayやno-cond-funcのカスタムルールを使いたい人がいたら、eslint-plugin-rulesdirを使って使ってみてください。