とーますメモ

Ruby on Rails / Goなどの学習メモ

【React】React × TypeScript × ESLint設定時のメモ

パッケージマネージャーはnpmを使用。
エディターはVSCode。VSCodeの設定とPrettierの設定は以前書いた。

MacでVSCodeを使用してみた - とーますメモ
【VSCode】 フロントエンド開発の使う自分用のPrettier設定まとめ - とーますメモ

Next.jsインストール

$ npx create-next-app "プロジェクト名"

/pagesを/srcに移す

ルートディレクトリが肥大化しわかりづらくなるため移動するのが現在のところベストプラクティスっぽい。
✨Next.js入門✨ 思考停止・爆速開発テンプレ 【TypeScript+ESLint+Prettier】
Blog - Next.js 9.1 | Next.js

$ cd "プロジェクト名"
$ mkdir src && mv pages src

/pagesを/src直下に移したことで__app.jsとindex.jsで読み込んでいるCSSのパスが変わるので以下のように変更する

__app.js

# import '../styles/globals.css';
import '../../styles/globals.css';

index.js

# import styles from '../styles/Home.module.css'
import styles from '../styles/Home.module.css'

この時点で、以下のコマンドを打て、localhost:3000にアクセスすればサンプルページが表示される

$ npm run dev

次にTypeScriptをインストールするためにCtrl + Cで一旦止める

ReactにTypeScriptを導入

プロダクションでは使用しないので、「devDependencies」としてインストールする -D オプションを使う。

$ npm i -D typescript @types/react @types/react-dom @types/node

拡張子の変更

以下のJavaScriptファイルの拡張子をjsからtsxに変更する。TypeScriptはJavaScriptの上位互換なので変更しても動作する。

src/pages/index.js → src/pages/index.tsx
src/pages/_app.js → src/pages/_app.tsx
src/pages/api/hello.ts → src/pages/api/hello.ts

helloはJSXを使用しない純粋なTypeScriptファイルなので拡張子はtsxではなく、tsを使用する。
【TypeScript】.ts拡張子と.tsx拡張子 - Qiita

Next.jsでTypeScriptの環境を構築する|Playground発!アプリ開発会社の技術ブログ
上記のサイトさんと同じように既存のファイルをTypeScriptのフォーマットに変更していく。

tsconfig.jsonを設定

以下の内容を設定

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "isolatedModules": true,
    "resolveJsonModule": true,
    "noEmit": true,
    "jsx": "preserve",
    "sourceMap": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": true,
    "removeComments": false
  },
  "exclude": ["node_modules"],
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
}

以下のサイトを参考にした
【入門】create-next-appでNext.jsとTypeScript環境を構築 | モグモグ
tsconfig.jsonの全オプションを理解する(随時追加中) - Qiita
Next.jsでTypeScriptの環境を構築する|Playground発!アプリ開発会社の技術ブログ
React with TypeScript: Best Practices - SitePoint

ESLintの設定

最終的に以下をインストール

$ npm install -D eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y eslint-config-prettier eslint-plugin-jest

インストールされる各プラグインについて

eslint

ESLint本体
適用されるルール: List of available rules - ESLint - Pluggable JavaScript linter

eslint-plugin-react

Reactのルール
適用されるルール:
GitHub - yannickcr/eslint-plugin-react: React specific linting rules for ESLint

eslint-plugin-react-hooks

React-Hooksのルール

@typescript-eslint/eslint-plugin と @typescript-eslint/parser

TypeScriptのルールと、ESLintがTypeScriptをパースすることを許容するパーサー

eslint-plugin-jsx-a11y

Webアクセシビリティー関連のルール
適用されるルール
eslint-plugin-jsx-a11y - npm

eslint-plugin-prettier

ESLintからPrettierを実行できる。ただしPrettier自体は別にインストールしている必要がある。

以前の記事でインストール済みなので、Prettier自体のインストールは省略
【VSCode】 フロントエンド開発の使う自分用のPrettier設定まとめ - とーますメモ

公式推奨が変わったため、eslint-plugin-prettierをいれない方針にする

詳細は以下のサイトさんを参考
Prettier と ESLint の組み合わせの公式推奨が変わり plugin が不要になった
eslint-plugin-prettier を ESLint から 分離するサンプル – Intellij IDEA の設定変更も | DevelopersIO

要は、ESLintとPrettierを個別に使用する方針にした。
こうすることでesllint-plugin-prettierが原因で起こる以下の決定をなくせる。

・エディターに赤いニョロニョロがたくさん出てくる。Prettier は format のことを気にしなくてもいいようにさせるツールなのに、フォーマットの警告が前面にでてきてしまう。
・直接 Prettier を実行するより遅い
・レイヤーをひとつ挟んでおり、不整合が起きる可能性がある

Prettier と ESLint の組み合わせの公式推奨が変わり plugin が不要になった

eslint-config-prettier

Prettierと競合するルールをオフにしてくれる

eslint-plugin-jest

Jest用のルール

設定ファイルの作成及び内容

以下のコマンドで設定ファイルを作成

$ npx eslint --init

回答内容は以下
How would you like to use ESLint?
=> To check syntax, find problems, and enforce code style

What type of modules does your project use?
=> JavaScript modules (import/export)

Which framework does your project use?
=> React

Does your project use TypeScript?
=> Yes

Where does your code run?
=> Browser

How would you like to define a style for your project?
=> Use a popular style guide

Which style guide do you want to follow?
=> Standard: https://github.com/standard/standard

What format do you want your config file to be in?
=> JavaScript

Would you like to install them now with npm?
=> Yes

.eslintrcが出力されるので、それをカスタマイズ。最終的に以下にした。

module.exports = {
  env: {
    browser: true,
    es2021: true,
    jest: true,
  },
  extends: [
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:jsx-a11y/recommended",
    "prettier",
  ],
  parser: "@typescript-eslint/parser",
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 12,
    sourceType: "module",
  },
  plugins: ["react", "react-hooks", "@typescript-eslint", "jsx-a11y"],
  rules: {
    "react/prop-types": "off",
    "react/react-in-jsx-scope": "off",
  },
  settings: {
    react: {
      version: "detect",
    },
  },
};

設定オプションについては以下のサイトさんの解説が良かった。
https://t-yng.jp/post/understand-eslint

ちなみに.eslintignoreは以下を設定

**/node_modules
**/.next/**
**/dist/**
*.config.js
.*lintrc.js

VSCodeにESLintの拡張をインストール

インストール後に、settings.jsonに以下の設定を入れれば保存時にESlint autofixがかかる。

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

ESLintとPrettierについて

上記でも書いたが個別に動かすの方針。
VSCodeを使っているので、通常はESLintとPrettierはVSCodeの自動フォーマット機能を使用し、npm scriptsを使うときは一括でlintやフォーマットを行いたいケースという風に使い分けする。

ちなみにnpm scriptsは以下のように設定する。

"scripts": {
    "lint": "run-p -l -c --aggregate-output lint:*",
    "lint:eslint": "eslint .",
    "lint:prettier": "prettier --check .",
    "fix": "run-s fix:prettier fix:eslint",
    "fix:eslint": "npm run lint:eslint -- --fix",
    "fix:prettier": "npm run lint:prettier -- --write",
    "test": "run-p -l -c --aggregate-output lint:* unit",
    "unit": "jest"
}

ESLint, Prettier, VS Code, npm scripts の設定: 2021春

ちなみに上記のrun-pを動作させるためには[npm-run-all]のパッケージをインストールする必要がある。
npm run のスクリプトを連続実行・並列実行する (npm-run-all) | まくまくNode.jsノート



[参考]
ESLint のススメ
✨Next.js入門✨ 思考停止・爆速開発テンプレ 【TypeScript+ESLint+Prettier】
ESLint, Prettier, VS Code, npm scripts の設定: 2021春