LoginSignup
79
77

More than 1 year has passed since last update.

React × Typescript × ESLint × Prettier × VSCodeなSetup

Last updated at Posted at 2020-03-18

初投稿から一年くらい経って、各種ライブラリも少し様変わりしたので書き直しました。
21spring verです。

こちらでメモしつつ、変更したのでよかったら参照ください。
https://zenn.dev/sh090/scraps/3a6fed549d4716

チェケラ

はじめに

create react app with tsなプロジェクトにeslintとprettierを入れる記事です。

やりたいこと

  1. react × typescript なLint設定
  2. Lintエラーの解消
  3. VScode保存時に自動整形

3は別記事がたくさんありますが一応

注意書きみたいなの

  • node, yarnがinstallされてる前提で話進めます
  • yarn 使います
  • Create React App 使います
  • style guide はAirbnb
  • ルールは各プラグインの推奨設定 + α
各種version
packages Version
react 17.0.2
react-scripts 4.0.3
eslint 7.20.0
typescript 4.1.2

1. プロジェクト作成 :hatching_chick:

プロジェクト作る。

yarn create react-app react-app --template typescript

eslint --init ここでairbnbを選択します。

yarn run eslint --init
回答内容
✔ How would you like to use ESLint? · style
✔ What type of modules does your project use? · esm
✔ Which framework does your project use? · react
✔ Does your project use TypeScript? · No / Yes
✔ Where does your code run? · browser
✔ How would you like to define a style for your project? · guide
✔ Which style guide do you want to follow? · airbnb
✔ What format do you want your config file to be in? · JavaScript

2. package入れてく :package:

eslint --init の質問で npm でインストールしないって選択したので、手動インストールする必要がある。

また prettier 関連のパッケージもインストールします。

airbnb

eslint-config-airbnb - npm
以下のコマンド で依存関係のパッケージも良い感じにインストールしてくれる

$ npx install-peerdeps --dev eslint-config-airbnb
質問
It seems as if you are using Yarn. Would you like to use Yarn for the installation?

Yarn使ってるんで y

typescript-eslint

@typescript-eslint/eslint-plugin - npm

$ yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser

prettier

prettier/eslint-config-prettier

$ yarn add -D prettier eslint-config-prettier

3. 設定 :gear:

.eslintrc.js

extends 追記

.eslintrc.js
extends: [
    'plugin:react/recommended',
    'airbnb',
+   'airbnb/hooks',
+   'plugin:@typescript-eslint/recommended',
+   'plugin:@typescript-eslint/recommended-requiring-type-checking',
+   'prettier',
],

parserOptions 追記

eslintrc.js
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 12,
    sourceType: 'module',
+   tsconfigRootDir: __dirname,
+   project: ['./tsconfig.json'],
  },

.prettierrc :link:

作ります。
Options一覧

.prettierrc
{
    "singleQuote": true
}

衝突ルール検出

$npx eslint-config-prettier 'src/**/*.{js,jsx,ts,tsx}'
No rules that are unnecessary or conflict with Prettier were found.

package.json

package.json に script 追記。 eslintConfigを除去。

package.json
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
+   "lint": "eslint --ext .ts,.tsx ./src",
+   "fix": "yarn format && yarn lint:fix",
+   "format": "prettier --write 'src/**/*.{js,jsx,ts,tsx}'",
+   "lint:fix": "eslint --fix 'src/**/*.{js,jsx,ts,tsx}'",
    "eject": "react-scripts eject"
  },
- "eslintConfig": {
-   "extends": "react-app"
- },

.eslintignore

作ります

.eslintignore
build/
public/
**/node_modules/
*.config.js
.*lintrc.js

vscode で .eslintignore 無しで src配下だけ eslintで見てほしいときの書き方がわからなかったので、 知ってる方いたら教えて下さい。
まぁ置いといて安定な気もする。

4. Lintエラー対応 :syringe:

yarn lint してみる。まぁエラーでる。
ソース修正、ルールを追記していく。

rule を追記する

とりあえずLintエラー解消のための最小設定

import/resolver , import/extensions :link:

拡張子が ts or tsx なファイルのインポートが解釈されない。
rules および settingsに追記する。

eslintrc.js
  rules: {
+   'import/extensions': [
+     'error',
+     {
+       js: 'never',
+       jsx: 'never',
+       ts: 'never',
+       tsx: 'never',
+     }
+   ]
  },
eslintrc.js
+ settings: {
+   'import/resolver': {
+     node: {
+       paths: ['src'],
+       extensions: ['.js', '.jsx', '.ts', '.tsx']
+     }
+   }
+ }

react/jsx-filename-extension :link:

JSXを含むファイルの拡張子を制限するルール。 .tsx なんぞ知らんぞと言われてるのでルール追記。

eslintrc.js
+   'react/jsx-filename-extension': [
+     'error',
+     {
+       extensions: ['.jsx', '.tsx'],
+     }
+   ],

react/react-in-jsx-scope :link:

JSXを使用する場合に React のインポートを強制するルール
ver17.0から JSXの変換方式変わったのでいらない。のでoffる

eslintrc.js
+   'react/react-in-jsx-scope': 'off',

no-void :link:

reportWebVitals.tsno-floating-promises 回避のために void 演算子 使います
Effect Hook でも void 使う箇所ある

変数の代入や式の戻り値 以外のでの使用 (すなわち文としての使用)ではおkとする

eslintrc.js
+   'no-void': [
+     'error',
+     {
+       allowAsStatement: true,
+     }
+   ]

ソース修正

全体

import React 消す

- import React from 'react';

App.tsx

アロー関数にして VFCつけて上げる

App.tsx
-function App() {
-  return (
+const App: VFC = () => (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.tsx</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
-}

reportWebVitals.ts

void つけてあげる

reportWebVitals.ts
+const reportWebVitals = (onPerfEntry?: ReportHandler): void => {
  if (onPerfEntry && onPerfEntry instanceof Function) {
+    void import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }): void => {
      getCLS(onPerfEntry);
      getFID(onPerfEntry);
      getFCP(onPerfEntry);
      getLCP(onPerfEntry);
      getTTFB(onPerfEntry);
    });
  }
};
$yarn lint    
yarn run v1.22.10
$ eslint --ext .ts,.tsx ./src
✨  Done in 6.77s.

prettier --write も忘れずに

VSCode :vs:

ファイル保存時に自動整形したい。
とりあえず、拡張機能はインストールしておきましょう。
ESLint - Visual Studio Marketplace
Prettier - Code formatter - Visual Studio Marketplace

eslint

settings.json
{
    "eslint.packageManager": "yarn",
    "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true
    },
}

prettier

ts, tsxのみな設定

settings.json
{
    ...
+   "[typescript]": {
+       "editor.defaultFormatter": "esbenp.prettier-vscode",
+       "editor.formatOnSave": true
+   },
+   "[typescriptreact]": {
+       "editor.defaultFormatter": "esbenp.prettier-vscode",
+       "editor.formatOnSave": true
+   }
}

おわりに :tea:

とりあえず「Lintエラー解消目的な構成」なので rules とか tsconfig.json とか適宜調整が必要です。

とはいっても、ただルールをoffるのではなく、 「〇〇の場合のみ許可する」みたいな設定にしたほうがよいと思うので経験に基づくセンスが問われますね。
それこそ、現場によって様々だと思います。
あなたの秘伝のタレ(.eslintrc)、教えていただけるとうれしいです:smile:

参考 :love_letter:

79
77
4

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
79
77