React+Vite+ESLint+Prettier 설정하기

김지원·2023년 3월 13일
8

Frontend

목록 보기
18/27

Prettier, ESLint를 배우고 코드 가독성을 위한 관리가 필수라는 걸 깨달았다. 내 코드를 읽는 다른 사람을 위해서도 코드를 작성하는 나를 위해서도 적절한 포맷팅이 필요하기 때문에! ESLint와 Prettier을 설정해보자.

Mac OS로 넘어온 이후 다시 Prettier과 ESLint 설정하는 데 계속 충돌이 일어나서 그런지 eslint를 실행하려고 할 때마다 아래 에러를 만났다..

ESLint couldn't find the config "react-app" to extend from.

좋은 레퍼런스 덕분에 성공적으로 설정할 수 있었고👍🏻!!
처음부터 차근차근 ESLint와 Prettier 설정하는 법을 알아봅시다.
출처는 여기다. Medium에 정말 좋은 글들이 많이 올라오는데 member 결제를 해야 하나 고민 중이다..

✨ 1. 프로젝트 생성하기

CRA(create-react-app)

yarn create react-app ${app_name} --template typescript
# or
npx create-react-app ${app_name} --template typescript

Vite-React

# npm 7+
npm create vite@latest ${app_name} -- --template ${템플릿 명}

# JavaScript react 템플릿 생성
npm create vite@latest ${app_name} -- --template react

# TypeScript react-ts 템플릿 생성
npm create vite@latest ${app_name} -- --template react-ts

프로젝트를 생성했으니 이제 ESLint를 설정해보자.

✨ 2. ESLint 설치

✅ Install ESLint

yarn add -D eslint
# or
npm install eslint --save-dev

developer dependency(--save-dev)로 설치해준다.

✅ Initialize the ESLint config file

npx eslint -init

그러면 eslint config file 생성 도우미가 실행될 것이다.

  • 마지막 단계에서 install with npm: No 선택했다면 아래 플러그인을 추가로 설치해준다.
yarn add -D eslint-plugin-react@latest @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest

타입스크립트를 사용할 경우 추가적으로 플러그인을 설치해준다.

yarn add -D eslint-plugin-import @typescript-eslint/parser eslint-import-resolver-typescript

✨ 3. Prettier 설치

✅ Install Prettier

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

✅ create the 🗒️ prettierrc file

touch .prettierrc

✨ 4. eslint, prettier 설정 파일 생성

.eslintrc.json 파일

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended"
  ],
  "overrides": [],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": ["react", "react-hooks", "@typescript-eslint", "prettier"],
  // 원하는 규칙 추가하기
  "rules": {
    "quotes": ["error", "single"],
    "no-duplicate-imports": "error",
    "no-console": ["warn", { "allow": ["warn", "error", "info"] }],
    "no-unused-vars": "error",
    "no-multiple-empty-lines": "error"
  },
  "settings": {
    "import/resolver": {
      "typescript": {}
    }
  }
}

rules 아래 자신이 원하는 규칙을 추가해주면 된다.

.prettierrc 파일

{
  "printWidth": 100, 
  "tabWidth": 2,
  "singleQuote": true, 
  "trailingComma": "es5",
  "useTabs": false,
  "arrowParens": "always",
  "bracketSpacing": true,
  "bracketSameLine": false
}

위 또한 자신의 원하는 옵션들별로 설정해주면 된다.

✨ 5. 명령어 자동화 - package.json

{
	...
	"format": "prettier --write --cache .",
	 "lint": "eslint src/**/*.{ts,tsx} --fix",
}
  • lint: 문제를 찾아내지만 수정하지 않음
  • lint fix : 문제를 찾아내고 수정한다
  • format : call prettier to fix the code style
profile
Make your lives Extraordinary!

0개의 댓글