(不要なはず)ESLintをインストール
VisualStudioでReactのプロジェクトを追加すればESLintは既に追加されるはずのため、この項目は不要なはずだが、念のため書いておく。
npm install --save-dev eslint
package.json
ファイルのdevDependencies
にeslint
の項目が追加される。
node_modules
内にもeslint
のフォルダが追加される。
ESLintの設定を行う
npm init @eslint/config
複数の質問を聞かれる。
今回は以下の順番で解答した。
- To check syntax, find problems, and enforce code style
- JavaScript modules (import/export)
- React
- No
- Browser
- Use a popular style guide
- Airbnb: https://github.com/airbnb/javascript
- JavaScript
- Yes
- npm
質問内容の詳細に関しては以下のサイトを確認
【VSCode】ReactとTypeScript、ESLint、Prettier、Airbnbで環境構築する手順
パッケージを追加
使用しないimportを自動削除するパッケージをインストール
npm i --save-dev eslint-plugin-unused-imports
Prettierを追加
npm i --save-dev prettier eslint-config-prettier
Prettierの設定を追加
ClientApp
フォルダ直下に.prettierrc.js
という名前のファイルを作成し、設定を書く。
module.exports = {
printWidth: 120,
singleQuote: true,
semi: true,
trailingComma: 'es5',
tabWidth: 2,
useTabs: false,
}
設定のオプションについては以下のサイトを参考に
ESLintの詳細設定を修正
.eslintrc.js
に書かれている詳細設定を修正する
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: ['airbnb', 'airbnb/hooks', 'prettier'],
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 12,
sourceType: 'module',
tsconfigRootDir: __dirname,
project: ['./tsconfig.json'],
},
plugins: ['react', 'unused-imports'],
ignorePatterns: ['build'],
rules: {
'no-use-before-define': 'off',
'import/prefer-default-export': 'off',
'unused-imports/no-unused-imports': 'error',
'unused-imports/no-unused-vars': [
'warn',
{
vars: 'all',
varsIgnorePattern: '^_',
args: 'after-used',
argsIgnorePattern: '^_',
},
],
'react/function-component-definition': [
2,
{
namedComponents: 'arrow-function',
unnamedComponents: 'arrow-function',
},
],
'no-param-reassign': [2, { props: false }],
'import/extensions': [
'error',
{
js: 'never',
jsx: 'never',
},
],
'react/jsx-filename-extension': [
'error',
{
extensions: ['.jsx', '.tsx'],
},
],
'react/prop-types': 1,
'no-void': [
'error',
{
allowAsStatement: true,
},
],
'react/jsx-uses-react': 'off',
'react/react-in-jsx-scope': 'off',
},
settings: {
'import/resolver': {
node: {
paths: ['src'],
extensions: ['.js', '.jsx'],
},
},
},
};
追加内容詳細は以下のサイトを確認
【VSCode】ReactとTypeScript、ESLint、Prettier、Airbnbで環境構築する手順
ESLintを適用させないフォルダ、ファイルを設定
ClientApp
フォルダ直下に.eslintignore
という名前のファイルを作成し、設定を書く。
build/
public/
**/node_modules/
*.config.js
.*lintrc.js
/*.*
VSCodeにESLintプラグインをインストール
検索内容:dbaeumer.vscode-eslint
ESLint – Visual Studio Marketplace
VSCodeにPrettierプラグインをインストール
検索内容:esbenp.prettier-vscode
Prettier – Code formatter – Visual Studio Marketplace
インストールした2つのプラグインを適用させる
左下の⚙をクリック 設定をクリック
右上のアイコンをクリック
開かれたページ(settings.json
)にの{}内に以下の内容を追加して保存する
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},