ESLintのキャッチアップ

はじめに

ESLintはJS/TSをやっていく上では必須になっていると思うんだけど、いまいち設定方法とか仕組みをわかってない。(特にプラグインでルール追加とかpresetとか)

ゼロから設定したり、vscodeプラグインとして使うのではなくて、コマンドラインとして単体で使ってみることで理解を深めたいと思う。

色々設定もありそうなので、ベストプラクティスは何なのかとかも探してみたい。

参考記事

ESLint最初の一歩

qiita.com

公式

eslint.org

ESLintの特色(上の記事の引用)

  • すべの検証ルールを自由にon/offできる
  • 自分のプロジェクトに合わせたカスタムルールを簡単に作れる
  • 豊富なビルトインルールに加えて、たくさんのプラグインが公開されている

インストール

$ npm i -D eslint
$ npx eslint -v
v8.14.0 
$ npx eslint test.js

Oops! Something went wrong! :(
ESLint: 8.14.0
ESLint couldn't find a configuration file. To set up a configuration file for this project, please run:
    npm init @eslint/config

.eslintrc.jsonファイルが内とだめっぽいな。 とりあえず、記事に記載のまま.eslintrc.jsonを作成。

{
    "extends": ["eslint:recommended"],
    "plugins": [],
    "parserOptions": {},
    "env": {"browser": true},
    "globals": {},
    "rules": {}
}

extendsのrecommendedがよく見るやつだな。設定ファイルを継承しているということかしら。 (eslintが推奨している設定を引き継いでいる的な)

$ npx eslint test.js

/home/xxxx/git/eslint_sample/test.js
  1:16  error  'name' is defined but never used  no-unused-vars
  2:42  error  'nama' is not defined             no-undef

✖ 2 problems (2 errors, 0 warnings)

ファイル名指定しなかったら、フォルダ内にある*.jsを検証するとあるが、うまく認識してくれなかったな、なぜでしょう。

ルールの追加

  • .eslintrc.jsonのrulesに追加する
    • セミコロンつけてないとエラー
      • semi : error
  • ルール:error | warn | off
  • ルールにはオプションを設定できる
    • ルールの指定が配列になって、2番目以降がオプション
    • semi : [ error, never] みたいない
    • neverだとセミコロンをつけてたらだめになる。
  • eslint/lib/rules以下にsemi.jsとかルール毎にJSファイルがあるっぽい

グルーバル変数を定義する

  • ESLintはファイル単位で静的チェックするのでグルーバル変数を教える必要がある
    • ローカルで試すと別にエラーにはなってないな
      • そんなことなかった$とかつけたらエラーになった
  • 方法
    • コメントで定義する
      • /* globals $ */
    • 設定ファイル(.eslintrc.json)のglobalsに定義する
      • "$" : false // falseは書き換え可能かどうか

環境設定をする

  • envプロパティで前提条件を設定できる
  • browser : true DOMAPIを有効にする
  • node : true Node.js固有の変数や構文が定義される
  • es6: true ES6で追加された構文や組み込みオブジェクトが使える
    • ただし、ES Modulesは有効にならない
      • parserOptionsにsoruceType : moduleを指定する
    • ES Modulesは強制的にstrictモードになったり既存をそのままモジュールとして扱うと壊れる可能性があるため特別扱いされている

ES6を活用するためのルール

  • たくさんあるらしい。とりあえずONにしてたらええんか?
    • このあたり良し悪しを把握したい
        "arrow-body-style": "error",
        "arrow-parens": "error",
        "arrow-spacing": "error",
        "generator-star-spacing": "error",
        "no-duplicate-imports": "error",
        "no-useless-computed-key": "error",
        "no-useless-constructor": "error",
        "no-useless-rename": "error",
        "no-var": "error",
        "object-shorthand": "error",
        "prefer-arrow-callback": "error",
        "prefer-const": "error",
        "prefer-rest-params": "error",
        "prefer-spread": "error",
        "prefer-template": "error",
        "rest-spread-spacing": "error",
        "template-curly-spacing": "error",
        "yield-star-spacing": "error"

ES6以降

  • envのes6: true以外にもparserOptionsでecmaVersionを指定する必要がある
    • デフォルトは5
      • 5ってなんだ
    • 5, 2015, 2016, 2017,2018,2019,...がある

エディタ上に表示する

  • vscodeでコードの問題をリアルタイムに表示するとか

プラグインを使う

  • 特定のライブラリやフレームワーク、実行環境に特化した検証はプラグインとして提供される
    • vue専用のチェックとかってことか
  • npm installでインストールして、pluginsプロパティを指定する
    • とあるが、extendsに指定しているのもあるな
      • extendsは推奨設定の指定、必須ではない。pluginをインストールして推奨設定を使うなら、extendsに指定する
  • npm install eslint-plugin-xxxxみたいな命名規則になっている
    • pluginsにはxxxxを指定する
    • 例:npm i eslint-plugin-node
  • rulesにてプラグインのルール設定をする

vue-cliからvue2.xのプロジェクトを生成したらいかのような.eslintrc.jsonが生成されてた。

module.exports = {
  root: true,
  env: {
    node: true,
  },
  extends: [
    "plugin:vue/essential",
    "eslint:recommended",
    "plugin:prettier/recommended",
  ],
  parserOptions: {
    parser: "@babel/eslint-parser",
  },
  rules: {
    "no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
    "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
  },
};

plugin:vue/essentialというのがvue独自のルールかな。pluginの指定がされてませんが。。どうなんだ。 もしかしたら、eslintのバージョンアップでpluginの指定は不要になったのかも?

plugin:vue/essentialと指定されているがnode_modulesにはeslint-plugin-vueとして存在しますな。以下が公式サイトっぽい。

eslint.vuejs.org

説明あったな。essentialが本当に基本的なもの。推奨されているものがすべて入っているわけではない。recommendedが推奨が全て入っている。って感じか。

"plugin:vue/essential" ... base, plus rules to prevent errors or unintended behavior.
"plugin:vue/strongly-recommended" ... Above, plus rules to considerably improve code readability and/or dev experience.
"plugin:vue/recommended" ... Above, plus rules to enforce subjective community defaults to ensure consistency

shareable configを使う

  • ESLintのルールは多い。
    • 組み込みルール:200以上
    • プラグイン:200以上公開されている
  • shareable configを使うと楽に共有できる。
    • 毎回eslintrc.jsonをコピペする必要なし
  • npmパッケージで設定をまとめられているので、npm installしてextendsプロパティを指定する
  • eslint-config-eslintはESLintチームの設定
    • eslint-config-xxxx命名規則。extendsにはxxxxの部分を指定する

ESLintのルール一覧

eslint.org

OSSプロジェクトのeslintrc.jsonの確認

vue3

  • extendsで何も指定されてないな、どういうことrulesに指定されているものしか利用してないのかな?

core/.eslintrc.js at main · vuejs/core · GitHub

TypeScript

  • plugins
    • @typescript-eslit,jsdoc,no-null,import
  • extendsはしていない

TypeScript/.eslintrc.json at main · microsoft/TypeScript · GitHub

React

  • extends: fbjs, prettier
  • root:trueこれがあると親ディレクトリにeslintrcがあるか見ないらしい
  • plugins
    • jest, no-for-of-loops, no-function-declare-after-return, react, react-internal
  • parser
    • babel-eslint // ふーむ。parserってどういうとき指定するんだー

react/.eslintrc.js at main · facebook/react · GitHub

なんか、各プロジェクト毎に違ってて、これさえ使えばOKみたいな感じではなさそうな気がするな。

あ、でも「eslint:recomended」がよいのかな。vue:recomendedとか、typescript:recomendedとか。

ESLintの公式ガイドやってみる

  • npm init @eslint/configでconfigファイルを生成できる
  • .eslintrcファイルはjs, yml, json形式が可能
  • config自動生成すると、eslint:recommendedがextendsに指定される
    • rulesで✔が入っているルール
      • あー、まずはこれだけでもいいのかも
  • eslintはルールをONにしたり、eslint-configをextendしない限りは何もlintしないらしい
  • package.jsoneslintConfigに指定しても良い
  • .eslintrc.jsonがあれば、そっち優先ぽい。eslintConfigは読まれない

eslint.org

cascading and hierarchy

eslint.org

メモ

以下も参考になる

zenn.dev