概要
ESLintとPrettierの必要なパッケージのインストールコマンドや設定のアレコレをプロジェクトを新規作成するたびにググっていて進歩がないので、本稿はその手順をメモするための記事です。
必要なもの
- ESLint
- eslint-config-prettier
- 📝 ESLintとPrettierのルールが競合する部分の解決に必要
- @typescript-eslint/eslint-plugin
- @typescript-eslint/parser
- prettier
ESLintのインストール
# yarn.lockを生成 $ yarn # ESLintのセットアップコマンドを実行 $ yarn run eslint --init
ESLintをTypeScriptに適用するためのパッケージをインストール
$ yarn add --dev @typescript-eslint/parser @typescript-eslint/eslint-plugin
Prettierのインストール
$ yarn add -D prettier eslint-config-prettier
ESLintとPrettierの設定の追記
.eslintrc.js
に追記
module.exports = { env: { browser: true, es2021: true }, extends: [ 'plugin:react/recommended', - 'standard-with-typescript' + 'standard-with-typescript', + 'prettier', ], overrides: [ ], parserOptions: { ecmaVersion: 'latest', - sourceType: 'module' + sourceType: 'module', + tsconfigRootDir: __dirname, + project: ['./tsconfig.json'], }, plugins: [ 'react' ], + 'ignorePatterns': [ + '.eslintrc.js' + ], rules: { + // errorは許可 + 'no-console': [ + 'error', + { + allow: ['error'], + }, + ], } }
.eslintignore
に追記
build/ public/ **/node_modules/ *.config.js .*lintrc.js /*.*
.prettierrc.js
に追記
module.exports = { printWidth: 120, singleQuote: true, semi: true, }
Package.jsonにコマンドを追加する
package.json
に追記
"start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", - "eject": "react-scripts eject" + "eject": "react-scripts eject", + "lint": "eslint --ext .ts,.tsx ./src", + "fix": "yarn format && yarn lint:fix", + "format": "prettier --write 'src/**/*.{js,jsx,ts,tsx}'", + "lint:fix": "eslint --fix 'src/**/*.{js,jsx,ts,tsx}'" }, "eslintConfig": { "extends": [