Rails にESLint + StyleLint + Prettier を導入してみた(Webpacker使用)

はじめに

  • ESLint : JSの静的解析に使用。
  • StyleLint : CSS、SCSSの静的解析に使用。
  • Prettier : フォーマッタとして使用

インストールするライブラリ

ESlintで静的解析、Prettierでフォーマットの修正が推奨されています。

they might conflict with Prettier! Use Prettier for code formatting concerns, and linters for code-quality concerns,

また、ESLintとprettierは別々に実行することが推奨されています。
参考=> Integrating with Linters · Prettier

StyleLintも同じ考え方で導入していきます。

それでは必要なライブラリをインストールしていきます。 -Dオプションで開発環境にのみインストールします。

npm install -D eslint prettier stylelint eslint-config-prettier stylelint-config-prettier stylelint-config-standard

設定ファイル

こちらは適宜修正してください。
配置する場所はプロジェクトの直下です。

.eslintrc.yml

env:
  browser: true
  es6: true
  jquery: true
extends:
  - eslint:recommended
  - prettier
parserOptions:
  ecmaVersion: 12
  sourceType: module
rules: {}

.prettierrc.yml

singleQuote: true
printWidth: 100

.stylelintrc.yml

extends:
  - stylelint-config-standard
  - stylelint-config-prettier
ignoreFiles:
  - app/views/**  # <= railsのメソッドが引っかかるので設定しています。

実行コマンド(一部)

  • ESLint
npx eslint --fix example.js
  • StyleLint
npx stylelint --fix example.css

補足: --fixオプションは自動修正を行ってくれます。

  • Prettier
npx prettier --write example.js

補足: --writeオプションは自動修正を行ってくれます。

Vscodeを使用して保存時に実行されるようにする

setting.jsonに設定を追加することで保存時に先程紹介したコマンドが実行されるようになります。

setting.json

  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,  // ESLint が保存時に実行される
    "source.fixAll.stylelint": true // StyleLintが保存時に実行される
  },
  "editor.formatOnSave": true,  // Pretteirが保存時に実行される。
  "editor.defaultFormatter": "esbenp.jjprettier-vscode",
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode" // 念の為なので無くても可
  },
  "prettier.disableLanguages": ["markdown"],
// ここから下も念の為なので無くても可
  "css.validate": false,
  "scss.validate": false,
  "typescript.validate.enable": false,
  "javascript.validate.enable": false,
  "less.validate": false