0
0

Reactプロジェクトのフォーマッター面のsetup

Last updated at Posted at 2024-09-03

Prettier+ESLintの併用

Prettier: ソースコードの整形を担うツール
ESLint: ソースコードの構文チェック

コードの整形とコードの構文チェックを両方担保するために、双方導入する。

Prettierの導入

参考

  • install
npm install --save-dev --save-exact prettier
  • prettierのルールを記述
echo {}> .prettierrc.json
touch .prettierignore
// .prettierrc.json
{
  "trailingComma": "es5",
  "tabWidth": 2,
  "semi": false,
  "singleQuote": true
}

format all files

npx prettier . --write

only checks that files are already formatted

npx prettier . --check

ESLintの導入

参考

  • ルールを記述
    下のコマンドを実行して、質問に答える。
npm init @eslint/config@latest

eslint.config.mjsができる

import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";
import pluginReact from "eslint-plugin-react";
import pluginReactJSXRuntime from "eslint-plugin-react/configs/jsx-runtime.js";

export default [
  {
    ignores: ["build/*"],
  },
  { files: ["**/*.{js,mjs,cjs,ts,jsx,tsx}"] },
  { languageOptions: { globals: globals.browser } },
  {
    settings: {
      react: {
        version: "detect",
      },
    },
  },
  pluginJs.configs.recommended,
  ...tseslint.configs.recommended,
  pluginReact.configs.flat.recommended,
  pluginReactJSXRuntime,
];

こんな感じのができる。

linterとprettierの競合解決

ここ全然わかってない、、
参考

npm install --save-dev eslint-config-prettier

eslint.config.mjs

import someConfig from "some-other-config-you-use";
import eslintConfigPrettier from "eslint-config-prettier";

export default [
  someConfig,
  eslintConfigPrettier,
];

huskyの導入

参考

npm install --save-dev husky lint-staged && npx husky init && echo "npx lint-staged" > .husky/pre-commit

モノレポ構成の場合は、precommitは以下。

cd client && npx lint-staged

package.jsonに以下を追加。

  "lint-staged": {
    "src/**/*.{js,jsx,ts,tsx}": [
      "npx eslint  --fix .",
      "npx prettier . --write"
    ]
  }

最初うまくいかなくてとりあえず入れ直したらhookが作られたんだけど何でだろ、、

色々初めてなので、間違っているところあったら教えてください!

0
0
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
0
0