[React] 협업을 위한 ESLint & Prettier 세팅하기

Lemon·2022년 11월 22일
1

React

목록 보기
20/21
post-thumbnail

VSCode Extension 설치

1) ESLint

자바스크립트 문법 체크 도구

2) Prettier

코드 Formatting 도구 (정렬, 세미콜론 등)


npm 패키지 설치

npm install -D prettier eslint-config-prettier eslint-plugin-prettier

ESLint와 Prettier 규칙의 충돌을 피하고 Prettier 오류를 Lint 에러로 보기 위해서는 eslint-config-prettier와 eslint-plugin-prettier를 설치해주면 된다. 각 패키지는 다음 역할을 한다.

  • eslint-config-prettier : 불필요하거나 Prettier와 충돌이(중복이) 일어나는 모든 ESLint의 rules를 무시한다. 즉 자바스크립트 문법 및 코드 품질 검사는 ESLint가, 코드 포맷은 Prettier가 검사하도록 만들어주는 것이다.
  • eslint-plugin-prettier : Prettier를 ESLint 규칙에 맞게 실행하게 하고 오류를 ESLint의 오류로 나타나게 해주는 기능을 하는 패키지이다. 즉 eslint-plugin-prettier 플러그인 설치를 통해 모든 Prettier 규칙 이 ESLint 규칙으로 추가된다고 볼 수 있기 때문에 ESLint 하나만 실행해도 문법검사와 formatting을 함께 실행 시킬 수 있다.

패키지 설치 확인

package.json 파일에서 추가 확인

"devDependencies": {
    "eslint-config-prettier": "^8.5.0",
    "eslint-plugin-prettier": "^4.2.1",
    "prettier": "^2.7.1"
}

dependencies와 devDependencies의 차이


.vscode/settings.json

프로젝트 루트 경로에 .vscode 폴더 생성하고 settings.json을 폴더 안에 생성한다.
이 파일에 작성한 내용으로부터 vscode에 관한 설정을 적용받는다.
이 폴더가 git에 함께 업로드 된다면, 이 파일이 포함된 프로젝트 폴더에서 작업을 하는 사용자는 해당 workplace에 대하여 .vscode/settings.json에 작성된 값에 따라 동일한 설정을 적용 받을 수 있다는 뜻이다.
여기에 포함되는 설정은 eslint/prettier 관련 설정에 국한되지 않는다. tap width나 terminal 관련한 설정 또한 포함되어 다른 팀원들의 에디터에 영향을 미칠 수 있으므로 주의가 필요하다.
이러한 이유로 사용할 예정이라면 컨벤션에 맞는 내용을 작성해 사용하고, 그렇지 않을 예정이라면 .gitignore에 추가해둘 것을 권장한다.


설정 하기

다양한 설정 파일이 존재할 경우 다음과 같은 순서로 설정이 적용된다.
settings.json.editorconfig.prettierrc
아래 설정들은 자동 포맷팅을 위한 최소한의 사항일 뿐이므로 팀 컨벤션에 따라 원하는 옵션을 추가하거나, 빼도 무방하다.

💡아래의 3개 파일은 루트 폴더에 생성한다.

1) .vscode/settings.json

{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
	"editor.tabSize": 2,
  "editor.formatOnSave": true,
	"editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
  },
	"javascript.format.enable": false,
	"eslint.alwaysShowStatus": true,
	"files.autoSave": "onFocusChange"
}

2) .eslintrc

ESLint 규칙을 적용하는 파일

  • 팀원이 모두 맥 유저일 경우
{
  "extends": ["react-app", "plugin:prettier/recommended"],
  "rules": {
    "no-var": "warn", // var 금지
    "no-multiple-empty-lines": "warn", // 여러 줄 공백 금지
    "no-console": ["warn", { "allow": ["warn", "error"] }], // console.log() 금지
    "eqeqeq": "warn", // 일치 연산자 사용 필수
    "dot-notation": "warn", // 가능하다면 dot notation 사용
    "no-unused-vars": "warn", // 사용하지 않는 변수 금지
    "react/destructuring-assignment": "warn", // state, prop 등에 구조분해 할당 적용
    "react/jsx-pascal-case": "warn", // 컴포넌트 이름은 PascalCase로
    "react/no-direct-mutation-state": "warn", // state 직접 수정 금지
    "react/jsx-no-useless-fragment": "warn", // 불필요한 fragment 금지
    "react/no-unused-state": "warn", // 사용되지 않는 state
    "react/jsx-key": "warn", // 반복문으로 생성하는 요소에 key 강제
    "react/self-closing-comp": "warn", // 셀프 클로징 태그 가능하면 적용
    "react/jsx-curly-brace-presence": "warn" // jsx 내 불필요한 중괄호 금지
  }
}
  • 팀원 중 윈도우 유저가 있을 경우
{
  "extends": ["react-app", "plugin:prettier/recommended"], // prettier plugin을 lint로서 따른다는 것
  "rules": { // 정해진 규칙들 수정 가능
    "no-var": "warn", // var 금지
    "no-multiple-empty-lines": "warn", // 여러 줄 공백 금지
    "no-console": ["warn", { "allow": ["warn", "error"] }], // console.log() 금지
    "eqeqeq": "warn", // 일치 연산자 사용 필수
    "dot-notation": "warn", // 가능하다면 dot notation 사용
    "no-unused-vars": "warn", // 사용하지 않는 변수 금지
    "react/destructuring-assignment": "warn", // state, prop 등에 구조분해 할당 적용
    "react/jsx-pascal-case": "warn", // 컴포넌트 이름은 PascalCase로
    "react/no-direct-mutation-state": "warn", // state 직접 수정 금지
    "react/jsx-no-useless-fragment": "warn", // 불필요한 fragment 금지
    "react/no-unused-state": "warn", // 사용되지 않는 state
    "react/jsx-key": "warn", // 반복문으로 생성하는 요소에 key 강제
    "react/self-closing-comp": "warn", // 셀프 클로징 태그 가능하면 적용
    "react/jsx-curly-brace-presence": "warn", // jsx 내 불필요한 중괄호 금지
    "prettier/prettier": [
      "error",
      {
        "endOfLine": "auto"
      }
    ]
  },
	"env": {
      "browser": true // document, window 등의 브라우저 내장 객체들 조회시 ESLint 오류 없이 작업
   },
}

3) .prettierrc

Prettier 규칙 설정하는 파일

{
  "tabWidth": 2, 
  "endOfLine": "lf", 
	"arrowParens": "avoid", 
	"singleQuote": true, // 문자열을 사용 할 때에는 ' 를 사용
}

추가 옵션들은 Prettier Options에서 확인해서 수정하면 된다.


3파일을 모두 만든 프로젝트 폴더의 형태이다.

이렇게 하면 설정이 완료된다.

참고 링크
🔗 https://seogeurim.tistory.com/15?category=981579

추가로 보면 좋을 자료
🔗 https://www.daleseo.com/eslint-config/

profile
프론트엔드 개발자 가보자고~!!

0개의 댓글