TypeScript × Reactでeslintを使う時
はじめに
初めまして。初めての記事になりますが、今回はTypeScript × React環境のeslintをテーマに書いていきます。
環境
- Node.js
- TypeScript
- React
- yarn
誰が使うことを想定するか
TypeScriptを全く触ったことがない人間が触ることを想定します。
eslintのrulesであまり細かいルールは定めず、TypeScriptとReactのルールを基本的に遵守します。
実装と注意点
これから実際のコードを見ていきます。いくつか引っ掛かりやすい注意点があるので確認していきましょう。
{
"eslint.run": "onSave",
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
"source.fixAll.stylelint": true
},
"debug.openDebug": "openOnSessionStart",
"typescript.tsdk": "node_modules/typescript/lib",
"files.eol": "\n",
"stylelint.validate": ["css", "less", "postcss", "typescriptreact"],
"[log]": {
"editor.wordWrap": "off",
"files.insertFinalNewline": true
}
}
eslintはターミナル上でyarn lint
と打つことで動作させられます。
eslint.run: "onSave"
で保存時に自動でeslintが動くようにします。
source.fixAll.eslint": true
で保存時にeslintでエラーを出す部分が自動で整形されます。これは本来falseにしておくべきですが(整形はprettierに任せるべき)今回は複雑なrulesも設定しないので使いやすさの観点からtrueにします。
editor.formatOnSave
これは絶対にtrueにしましょう。
module.exports = {
root: true,
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:react-hooks/recommended',
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/eslint-recommended',
'prettier',
],
plugins: ['@typescript-eslint', 'react'],
parser: '@typescript-eslint/parser',
env: {
browser: true,
node: true,
es6: true,
},
settings: {
react: {
version: 'detect',
},
},
parserOptions: {
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
ecmaFeatures: {
impliedStrict: true,
},
rules: {
'react/react-in-jsx-scope': 'off',
'react/prop-types': 'off',
'react/self-closing-comp': 'error',
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'error',
'prefer-template': 'error',
'@typescript-eslint/consistent-type-imports': 'error',
'@typescript-eslint/explicit-module-boundary-types': 'off',
//ここから下がeslintのドキュメントにあるrules
'no-dupe-args': ['error'],
'no-dupe-keys': ['error'],
'no-unreachable': ['error'],
//'brace-style': ['error', 'allman', { allowSingleLine: true }],
},
}
単純なものだけ設定しています。気になる方https://eslint.org/docs/latest/rules/ を参考にしてください。
ここで注意する点はextends[]
の中身は後に書かれている方が優先されるという点です。これはエラーを探すうえでも役に立ったので覚えておきましょう。
{
"singleQuote": true,
"semi": false,
"quoteProps": "consistent",
"jsxBracketSameLine": false,
"singleAttributePerLine": true
}
prettierの設定は上のとおりです。気になる人はhttps://prettier.io/docs/en/options.htmlを確認してください。
まとめ
いかがでしたでしょうか。
eslintの設定はこだわりたくなりますが、あまり書かないに越したことはありません。どの環境にも順応できるようにTypeScriptの地力を鍛えていきましょう。
質問や指摘はzennでもTwitterでもぜひお願いします!
Discussion