やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

リントをインストールする【ESLint】

 リントは開発用ツールのひとつで、ソースコードを実行せずテキスト解析して問題点を洗い出してくれる。

前提

情報源

手順

プロジェクト用ディレクトリを作成する

PJ_NAME=hello-es-lint
mkdir $PJ_NAME
cd $PJ_NAME

プロジェクトを初期化する

npm init

 package.jsonが作成される。

ESLintをインストールする

sudo npm install -g eslint

構成ファイルを設定する

npm init @eslint/config
✔ How would you like to use ESLint? · problems
✔ What type of modules does your project use? · esm
✔ Which framework does your project use? · none
✔ Does your project use TypeScript? · No / Yes
✔ Where does your code run? · browser
✔ What format do you want your config file to be in? · JavaScript
Local ESLint installation not found.
The config that you've selected requires the following dependencies:

eslint@latest
✔ Would you like to install them now with npm? · No / Yes

確認する

バージョン確認

$ eslint --version
v8.12.0

ヘルプ確認

ヘルプ内容

eslint [options] file.js [file.js] [dir]

Basic configuration:
  --no-eslintrc                   Disable use of configuration from .eslintrc.*
  -c, --config path::String       Use this configuration, overriding .eslintrc.* config options if present
  --env [String]                  Specify environments
  --ext [String]                  Specify JavaScript file extensions
  --global [String]               Define global variables
  --parser String                 Specify the parser to be used
  --parser-options Object         Specify parser options
  --resolve-plugins-relative-to path::String  A folder where plugins should be resolved from, CWD by default

Specifying rules and plugins:
  --plugin [String]               Specify plugins
  --rule Object                   Specify rules
  --rulesdir [path::String]       Load additional rules from this directory. Deprecated: Use rules from plugins

Fixing problems:
  --fix                           Automatically fix problems
  --fix-dry-run                   Automatically fix problems without saving the changes to the file system
  --fix-type Array                Specify the types of fixes to apply (directive, problem, suggestion, layout)

Ignoring files:
  --ignore-path path::String      Specify path of ignore file
  --no-ignore                     Disable use of ignore files and patterns
  --ignore-pattern [String]       Pattern of files to ignore (in addition to those in .eslintignore)

Using stdin:
  --stdin                         Lint code provided on <STDIN> - default: false
  --stdin-filename String         Specify filename to process STDIN as

Handling warnings:
  --quiet                         Report errors only - default: false
  --max-warnings Int              Number of warnings to trigger nonzero exit code - default: -1

Output:
  -o, --output-file path::String  Specify file to write report to
  -f, --format String             Use a specific output format - default: stylish
  --color, --no-color             Force enabling/disabling of color

Inline configuration comments:
  --no-inline-config              Prevent comments from changing config or rules
  --report-unused-disable-directives  Adds reported errors for unused eslint-disable directives

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

Miscellaneous:
  --init                          Run config initialization wizard - default: false
  --env-info                      Output execution environment information - default: false
  --no-error-on-unmatched-pattern  Prevent errors when pattern is unmatched
  --exit-on-fatal-error           Exit with exit code 2 in case of fatal error - default: false
  --debug                         Output debugging information
  -h, --help                      Show help
  -v, --version                   Output the version number
  --print-config path::String     Print the configuration for the given file

実行する

 以下のコマンドで実行できる。

eslint yourfile.js

 テスト用に問題があるJSファイルを作ってみる。

0.js

function hello(name) {
    document.body.textContent = "Hello, " + nama + "!"
}
hello("World");

 実行する。

$ eslint 0.js

/tmp/work/hello-es-lint/0.js
  1:16  error  'name' is defined but never used  no-unused-vars
  2:45  error  'nama' is not defined             no-undef

✖ 2 problems (2 errors, 0 warnings)

 エラーメッセージは次のようになっている。

  行番号:列番号  種類    メッセージ                        ルール名
  1:16          error  'name' is defined but never used  no-unused-vars
  2:45          error  'nama' is not defined             no-undef

 英語だが、プログラマなら見覚えのある単語なので察しはつくだろう。和訳すると以下のような感じ。

  • 0.jsファイルの1行目16列目でエラーです。変数nameは定義されていますが使用されていません
  • 0.jsファイルの2行目45列目でエラーです。変数namaは定義されていません

 よくみるとタイポしている。nameのつもりがnamaになっている。このエラーで気づける。

 このコードをブラウザで実行したらHello, undefined!という文字列がHTMLのbodyに表示されるだろう。そのときにも気付けるはず。え、だったらべつにリントなんていらないのでは? と思ってしまうが、ライブラリや関数など、表示されないコード部分に対して可視化してくれるから嬉しいのだ。

ルールを追加する

 以下のような設定ファイルがあるはず。

.eslintrc.js

module.exports = {
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaVersion": "latest",
        "sourceType": "module"
    },
    "rules": {
    }
}

 rulessemiを追加する。

...
    "rules": {
        "semi": "error"
    }
}

 再実行すると「セミコロンがない」と叱ってくれるようになる。

$ eslint 0.js

/tmp/work/hello-es-lint/0.js
  1:16  error  'name' is defined but never used  no-unused-vars
  2:45  error  'nama' is not defined             no-undef
  2:55  error  Missing semicolon                 semi

✖ 3 problems (3 errors, 0 warnings)
  1 error and 0 warnings potentially fixable with the `--fix` option.

 教えてくれてありがとう。君のおかげでいいコードが書けそうだ。

ルール詳細

 エラーに出力されていたno-unused-varsno-undefsemiはルール名。ルール一覧で詳細がわかる。

所感

 便利そうだけど、自動で修正してほしいわ。いっそコード全部書いてほしいわ。それは無理でも整形くらいはしてほしい。ということで、次はフォーマッタを使ってみる。

対象環境

$ uname -a
Linux raspberrypi 5.10.63-v7l+ #1496 SMP Wed Dec 1 15:58:56 GMT 2021 armv7l GNU/Linux