4
3

More than 1 year has passed since last update.

React Native(Expo + TypeScript)用にEslint,Prettierの設定をする

Last updated at Posted at 2021-03-08

プロジェクト毎に設定するが、毎回忘れてしまうため自分用のメモとして作成
Javascript用の設定はこちら

##ESLintとは
Javascriptの静的検証ツール
ESLintを使用すると、誤字、セミコロン、クオート、未使用の変数やブロックなど開発中に気づきにくいミスが見つけやすくなります。

##ESLintの導入
###VSCodeの拡張機能からESlintをインストールする
スクリーンショット 2021-09-28 23.25.54.png

###インストール

yarn add -D eslint typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-react-hooks

###初期設定
初期化して.eslintrc.jsファイルを生成

npx eslint --init

以下の設定で、質問に答えていく

√ How would you like to use ESLint? · To check syntax, find problems, and enforce code style
√ What type of modules does your project use? · JavaScript modules (import/export)
√ Which framework does your project use? · react
√ Does your project use TypeScript? · Yes
√ Where does your code run? · node
√ How would you like to define a style for your project? · prompt
√ What format do you want your config file to be in? · TypeScript
√ What style of indentation do you use? · 4
√ What quotes do you use for strings? · single
√ What line endings do you use? · unix
√ Do you require semicolons? · Yes

###.eslintrc.js を修正

.eslintrc.js
module.exports = {
  env: {
    es2021: true,
    node: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:@typescript-eslint/recommended',
    'prettier',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 12,
    sourceType: 'module',
  },
  plugins: ['react', '@typescript-eslint', 'react-hooks'],
  rules: {
    indent: ['error', 2],
    'linebreak-style': ['error', 'unix'],
    quotes: ['error', 'single'],
    semi: ['error', 'always'],
    'react-hooks/rules-of-hooks': 'error',
    'react-hooks/exhaustive-deps': 'warn',
    'react/display-name': 0,
    'react/prop-types': 0,
  },
  settings: {
    react: {
      version: 'detect',
    },
  },
};

##Prettierとは
コードフォーマッター(ソースコードを整形してくれるツール)のこと。読み方はプリティア。

##Prettierの導入
###VSCodeの拡張機能からPrettierをインストールする
スクリーンショット 2021-09-28 23.27.11.png

###インストール

yarn add -D prettier eslint-config-prettier eslint-plugin-prettier

###.prettierrc.js を追加

.prettierrc.js
module.exports = {
  jsxSingleQuote: true,
  singleQuote: true,
  trailingComma: 'all',
  printWidth: 100,
  endOfLine: 'lf',
};

##.vscode/settings.json を追加
これを設定することで、Ctrl+sでファイルを保存する際にコードフォーマットしてくれるので便利

settings.json
{
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
    },
}
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3