LoginSignup
26
12

More than 3 years have passed since last update.

eslint の設定で import をきれいにする

Last updated at Posted at 2020-10-23

はじめに

複数人で開発する際に「コーディングルールを揃えたい」というケースはよくあります。
各々が自由に開発していると、import の順番がバラバラになったりして、プルリクエストの際に本質的ではない変更が混在します。

私が香港のスタートアップで開発していたときは、チームメンバー全員が VSCode を利用しており、settings.json に

"editor.codeActionsOnSave": {
    "source.organizeImports": true,
},

を入れることで、統一していました。
しかし、エディタ(は宗教問題なので)を統一したくないケースもあると思いますので、 eslint で出来ればベターだと思います。

今回は、その方法をご紹介します。

実装

今回ご紹介するプラグインは import, unused-imports です。
まずはプラグインをインストールします。

yarn add -D eslint-plugin-import eslint-plugin-unused-imports

次に .eslint.yaml を下記のように変更します。

# .eslint.yaml
env:
  browser: true
  es2021: true
extends:
  - 'plugin:prettier/recommended'
  - 'prettier/@typescript-eslint'
  - 'prettier/react'

parser: '@typescript-eslint/parser'
parserOptions:
  ecmaFeatures:
    jsx: true
  ecmaVersion: 12
  sourceType: module
plugins:
  - react
  - '@typescript-eslint'
  - import
rules: 
  sort-imports: 0
  "import/order":
    - warn
    - groups:
        - builtin
        - external
        - internal
      alphabetize:
        order: asc

筆者の環境では VSCode の設定に、

"editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
},

が入っているので、ファイルを変更して保存した瞬間に import の順番が変わります。

修正前

image.png

修正後

image.png

しかし、このままでは不要な(利用していない)import が残っています。
これも自動で消したいです。

その設定を入れていきます。

# .eslint.yaml
...
plugins:
...
  - unused-imports
rules: 
...
  "@typescript-eslint/no-unused-vars": off
  unused-imports/no-unused-imports-ts: warn
...
修正後

Screen Shot 2020-10-23 at 14.45.21.png

不要な import が消えました。

おわりに

複数人で開発する時に、コードフォーマッタや elinter で記述ルールを揃えると開発速度が一気に加速します。

今回紹介した方法よりも良い方法や、他にも記述改善するためのテクニックがあればぜひ教えてください。

26
12
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
26
12