LoginSignup
1
1

More than 3 years have passed since last update.

ゼロからのESLint その2

Last updated at Posted at 2019-11-18

この記事はその1を読んでいる前提になります。

この記事に書かれていること

  • ルールの追加
  • Fix オプション (コードを自動修正)
  • ESLintの管轄外ファイルの作成

ファイル構造

ESLint_Plus
  ├── .eslintrc.json
  ├── .eslintignore 
  ├── .gitignore
  ├── node_modules
  │   └── たくさんあるから書かない
  │  
  ├── package.json
  └── src
      ├── app.js 
      └── noLint
           └──ignore.js

ルールの追加

eslintrc.json
{
    "extends": ["eslint:recommended"],
    "env": {"browser": true},
    "rules": {
      "quotes": ["warn", "double"],
      "space-before-blocks": ["warn", { "functions": "always" }]
    }
}

例として2つのルールを追加しました。

  • クォーテーションは全て「 "
  • 関数の後ろに空白必須

第一引数は警告のレベルを表しています。

  • error
  • warn
  • off

の三種類あります。今回はwarnレベルを使用

一旦設定終了

まずは実行

app.js
function hoge(text){
  console.log(text +'使ってみた')
}
hoge('ESLint')
terminal
$ npm run lint
/ESLint_Plus/src/app.js
  1:20  warning  Missing space before opening brace  space-before-blocks
  2:21  warning  Strings must use doublequote        quotes
  5:6   warning  Strings must use doublequote        quotes

✖ 3 problems (0 errors, 3 warnings)

こんな感じ、、
関数の後ろに空白がないのと、シングルクォーテーション使うなって怒られています。

このようにルールを追加していき、カスタマイズできます。

Fixオプションでコード整形

先ほど怒られた内容を一発修正する方法を示します。

package.json
{
  "name": "ESLint_Plus",
  "scripts": {
    "lint": "eslint src",
    "fix": "eslint --fix src"
  },
  "dependencies": {
    "eslint": "^6.6.0",
  }
}

eslintオプションの --fixを追記する。

$ npm run fix

eslintrcで指定したルール通り、自動でコード整形してくれる。
確認してみましょう。

app.js
function hoge(text) {
  console.log(text +"使ってみた")
}
hoge("ESLint")

整形されていることが確認できました!

ESLintの管轄外ファイルを作る

見出しで思いついた人もいるかもしれませんが、そうです、あれです。
Gitとかでもみるignoreです。

noLint内にJSファイルを置く

ignore.js
function ignore(text){
  console.log(text +'の管轄外')
}
ignore('ESLint')

eslintのignoreファイルを作成します。

.eslintignore
/src/noLint/**
$ npm run lint 

本来 src/noLint/ignore.js も対象ですが、.eslintignore で指定されたことで管轄外になります。

おわり

今回使ったコードはこちらです。

コードフォーマット(コード整形)はESLintで行うより、Prettier を使った方がいいです。

1
1
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
1
1