ASP.NET Core + Reactのプロジェクトにeslintとprettierを導入する
ASP.NET Core + Reactで作成したプロジェクトにTypeScriptを導入するで、ReactのプロジェクトにTypeScriptを導入しました。
このプロジェクトに対して、構文チェックやソースのフォーマットを自動で行うeslintとprettierを導入します。
eslintのルールには様々なものがありますが、ここでは以下のルールを使用します。
react用のルールeslintが推奨(recommended)しているルールtypescriptが推奨(recommended)しているルールprettierと共存するためのルール
VSCodeの拡張機能のインストール
eslintとprettierをVSCodeで動作させるための拡張機能をインストールします。
ASP.NET Core + Reactの開発環境をDockerで作成するの手順で環境を作成した場合は、以下の設定で、コンテナ起動時に自動で拡張機能をインストールしていますので、この操作は不要です。
.devcontainer.json
"extensions": [
"ms-dotnettools.csharp",
"editorconfig.editorconfig",
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode"
]
}以下の拡張機能をインストールします。
VSCodeの設定ファイルの修正
拡張機能を認識させるため、VSCodeの設定ファイルを作成します。
プロジェクトのルートディレクトリに.vscodeというフォルダを作成し、その中にsettings.jsonという名前のがいるを作成します。
- .devcontainer
- .devcontainer.json
- .vscode
- setting.json ←作成
ファイル保存時にprettierの機能でソースをフォーマットするように設定します。
また、Reactプロジェクトのパスも設定します。
settings.json{
"editor.codeActionsOnSave": {
"source.fixAll": true,
"source.organizeImports": true
},
"editor.formatOnType": true,
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"eslint.workingDirectories": ["./App.Web/ClientApp"]
}パッケージのインストール
必要なパッケージをインストールする前に、デフォルトでインストールされているeslint関連のパッケージを確認します。
package.jsonファイルに以下の記載があることを確認します。
package.json "eslint": "^8.18.0",
"eslint-config-react-app": "^7.0.1",
"eslint-plugin-flowtype": "^8.0.3",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-jsx-a11y": "^6.6.0",
"eslint-plugin-react": "^7.30.1",上記以外に、必要な以下のパッケージをインストールします。
- eslint-config-prettier
- eslint-plugin-react
- prettier
$ npm install eslint-config-prettier eslint-plugin-react prettier -Dpackage.jsonの修正
デフォルトで、package.jsonにeslintの設定が記載されています。
今回はeslintの設定は別ファイルで管理するため、package.jsonから設定を削除します。
package.json "eslintConfig": {
"extends": [
"react-app"
]
},eslintの設定ファイルの作成
.eslintrc.jsというファイル名で、Reactプロジェクトのルートディレクトリ(package.jsonと同じ階層)にファイルを作成します。
ルールは適宜変更してください。
.eslint.js// @ts-check
/** @type {import('eslint').Linter.Config} */
module.exports = {
root: true,
parserOptions: {
project: ['./tsconfig.json'],
},
extends: ['react-app', 'eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier'],
rules: {
'@typescript-eslint/explicit-module-boundary-types': 'off',
},
overrides: [
{
files: ['./.eslintrc.js'],
parserOptions: { project: null },
},
],
};src\setupProxy.jsについては、例外として、eslintのチェックは行わないようにします。
.eslintignoreというファイルを.eslint.jsと同じ階層に作成しておけば、特定のファイルはeslintのチェックを行わないようにできます。
src\setupProxy.jsprettierの設定ファイルの作成
.prettierrc.jsというファイル名で、同じ階層にファイルを作成します。
設定内容は適宜変更してください。
.prettier.js// @ts-check
/** @type {import('prettier').Options} */
module.exports = {
printWidth: 120,
tabWidth: 2,
singleQuote: true,
semi: true,
};以上で設定は完了です。