delhi09の勉強日記

技術トピック専用のブログです。自分用のメモ書きの投稿が多いです。あくまで「勉強日記」なので記事の内容は鵜呑みにしないでください。

【Reactの勉強】環境構築(Prettierの設定)

概要

前回に引き続き、環境構築を行う。
今回はPrettierの設定を行う。

prettier.io

適宜、以下の本を参考にさせて頂きながら進める。(以下、『りあクト!』)

oukayuka.booth.pm

バージョン

「Reactの勉強」で使用している主なソフトウェアのバージョンは以下の通り。

  • node: 15.5.0
  • react-create-app: 4.0.1
  • react: 17.0.1
  • react-dom: 17.0.1
  • typescript: 4.1.3
  • eslint: 7.17.0
  • prettier: 2.2.1

設定

Prettierをインストールする

以下のコマンドを実行してPrettierをインストールする。

$ npm install -D prettier
$ npm install -D eslint-plugin-prettier
$ npm install -D eslint-config-prettier

typesyncを実行する。

$ node_modules/typesync/bin/typesync

.eslintrc.jsにPrettierの設定を追加する。

以下の作者の方のリポジトリを見ながら、.eslintrc.jsにPrettierの設定を追加する。

github.com

.prettierrcを作成・設定する。

同様に、以下の作者の方のリポジトリを見ながら、.prettierrcというPrettierの追加設定用のファイルを作成・設定する。

github.com

ESLintとPrettierが衝突していないかの確認

本には以下のコマンドで確認できると書いてあったが、公式ドキュメントによると、eslint-config-prettierのバージョン7.0.0移行ではこのやり方ではないらしい。(私の環境のバージョンは7.1.0)

$ npx eslint --print-config .eslintrc.js | npx eslint-config-prettier-check

github.com

バージョン7.0.0以降では、任意の対象ファイルに対して以下のコマンドを実行するようである。

$ npx eslint-config-prettier path/to/main.js

※ 原理的には全ての対象ファイルに対して上記のコマンドを実行しないと、衝突していないことを100%担保したとはいえないが、フォーマットルールが共通なら、1ファイルサンプリングして実行してOKなら良いのでは?とのことのようである。

In theory you need to run the tool for every single file in your project to be 100% sure that there are no conflicting rules, because ESLint supports having different rules for different files. But usually you’ll have about the same rules for all files, so it is good enough to run the command on one file. But if you use multiple configuration files or overrides, you can provide several files check:

github.com

試しに以下の2ファイルに対して実行してみたが、衝突はなかった。

$ npx eslint-config-prettier index.tsx App.tsx
No rules that are unnecessary or conflict with Prettier were found.

VS Codeに自動フォーマットを設定する。

VS Codesettings.jsonに以下を設定する。

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

動作確認

まずは、VS Code上でtsxファイルのフォーマットを適当に崩してみて、保存すると、フォーマットが実行されることを確認する。

上記でフォーマットされた場合でも、ESLintの標準のフォーマット機能でフォーマットされた可能性もあるので、例えば、.prettierrcのprintWidthの値を小さくした場合に、ファイルがより短い文字数で改行されるようになることを確認する。

→ 確認できたが、.prettierrcの変更は、VS Codeを一度再起動しないと反映されないようだった。即時反映する方法があったら知りたい。

とりあえず、VS Code上からフォーマットはできたので、以上