WindowsのVisutal Studio CodeでESLintとPrettierを使い、ファイル保存時に自動的にコードをフォーマットしてくれるようにする手順です。ここではNuxt.jsのプロジェクトで試してみます。
Nuxtのプロジェクト作成
プロジェクト作成コマンド実行
コマンドプロンプトを開き、適当な作業フォルダでプロジェクトを作成します。
1 |
npx create-nuxt-app SampleProject |
以下の設定で実行してみました。Linting toolsでESLintやPrettierを選択できますが後で自分でインストールするので選択してません。

ESLintとPrettierのインストール
ESLintとPrettierのインストールコマンド実行
作成したプロジェクトに移動しESLintとPrettierをインストールします。開発用の機能なので-Dオプションを付けます。
1 2 |
cd SampleProject npm install -D eslint prettier |
ESLintとPrettierの連携設定
続いてESLintとPrettierの両者が整形処理を実行してしまわないようにする設定をします。先ほどのコマンドに続けて、以下コマンドを実行します。
1 |
npm install -D eslint-config-prettier |
ESLintの初期化
node_modules\.binフォルダの中にeslintのツールが入っているので、以下のコマンドでESLintの設定ファイルを作成します。
1 |
node_modules\.bin\eslint --init |
いくつか質問されるので適当に答えます。

.eslintrcの編集
プロジェクトフォルダに「.eslintrc.*」という名前の設定ファイルが作成されているので開きます。「What format do you want your config file to be in?」 の質問で答えた内容に応じて拡張子が.jsだったり.jsonだったりします。
以下は.jsonの例です。extendsの最後にprettierと追記します。extendsの一番最後に記述しないとうまく動かないことがあるそうです。

ちなみに.eslintrcの形式がJavaScriptだとこんな感じでエラー扱いになってしまって直すのにひと手間かかるので私は.eslintrcの形式はJSONが好みです。

VSCodeの拡張機能インストール
拡張機能のインストール
VSCodeの画面左側にある拡張機能タブを開いてESLintを検索し、インストールをクリックします。

同様にPrettierを検索し、インストールをクリックします。

保存時にフォーマットするよう設定
メニューからファイル→ユーザー設定→設定を選択。もしくは「Ctrl + ,」を実行。

検索欄にformatと入力して検索し、「Format On Save」にチェックを入れます。

フォーマッタの指定
何か適当なJavaScriptファイルを開きます。ここではnuxt.config.jsを使います。その状態でShift+Alt+Fを押すとフォーマットしてくれますが以下のようがダイアログが表示されますので「構成」ボタンをクリックします。

フォーマッタの選択を迫られるのでPrettierを選択します。

他の形式のファイル(.vueとか.jsonとか)を自動フォーマットしたい場合も同様です。
確認
ファイルを保存するとPrettierのフォーマットが走ることを確認します。

ESLintが構文チェックもしてくれています。

settings.jsonで直接編集
保存時の自動フォーマットやフォーマッタの指定はsettings.jsonに保存されています。直接開いて編集しても同様の結果になります。こちらを直接編集する方法がよく紹介されていますが、個人的には間違いにくいGUIの方が好きです。
