React + ESLint + Prettier + Typescript 세팅하기

만두·2021년 9월 6일
7

SI 업체에 있을때 그 정리안되고 난잡한 코드를 보고 난 저렇게 안짜야지 라는 생각을 하면서 잘 지키면서 살아오고 있었는데, 최근 React, VS Code를 알게되고 소스코드 포맷을 자동으로 체크해주는 ESLint, Prettier 라는 것도 알게되었습니다.
새로운 프로젝트를 만들때마다 정확하게 알지 못하고 사용했었는데 이번 기회에 제대로 알고 시작하고 싶고 찾아 보는것도 지쳐서 글을 남깁니다.

👻 ESLint란

ES LInt는 ES + Lint의 합성어입니다.

ES = ECMA Script 즉, Javascript를 의미합니다.
Lint = 버그나 의심스러운 구조체에 표시를 해주는 것을 의미합니다.

Linter는 코드를 정적으로 분석하기 때문에, 프로그램을 실행하지 않고도 안티 패턴등을 자동으로 검출해줍니다.

👻 Prettier란

코드를 미(美)적으로 보기좋게 포맷팅 해줍니다. 설정파일에 정해둔 규칙으로 코드 구조를 완전히 새로 작성해줍니다.

😏세팅하기

CRA Typescrpit 환경, VS Code를 이용합니다. 귀찮아서 한번에 세팅합니다.

1. 확장 프로그램 설치

eslint, prettier을 각각 검색후 설치해줍니다.

2. 터미널에서 eslint, prettier 설치

1. npm 또는 yarn 으로 설치합니다.

$ npm install eslint prettier --save-dev
or
$ yarn add -D eslint prettier

2. typescript 설치

$ npm install @typescript-eslint/eslint-plugin @typescript-eslint/parser --save-dev
or
$ yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser
  • typescript-eslint/parser : Typescript에서 ESLint를 사용할 수 있도록 해줍니다.
  • typescript-eslint/eslint-plugin : TypeScript 린팅(linting) 규칙을 실행할 수 있는 ESlint 플러그인

3. 기타 플러그인 설치

$ npm install eslint-config-prettier eslint-plugin-prettier eslint-plugin-react eslint-plugin-react-hooks --save-dev
or
$ yarn add --dev eslint-config-prettier eslint-plugin-prettier eslint-plugin-react eslint-plugin-react-hooks
  • eslint-config-prettier : prettier와 충돌할 수 있는 ESLint 규칙을 비활성화
  • eslint-plugin-prettier : prettier와 규칙을 ESLint 규칙으로 추가시킵니다. prettier와 모든 규칙이 ESLint로 들어오기 때문에 ESLint만 실행하면 됩니다.

3. .eslintrc, .prettierrc 세팅

루트 폴더에 파일을 생성해주세요.

.eslintrc

{
    "parser": "@typescript-eslint/parser",
    "extends": ["plugin:@typescript-eslint/recommended", "plugin:prettier/recommended"],
    "plugins": ["@typescript-eslint", "prettier"],
    "ignorePatterns": ["node_modules/"],
    "env": {
        "browser": true,
        "node": true
    },
    "rules": { "@typescript-eslint/explicit-module-boundary-types": "off" }
}
  • parser : ESLint는 구문 분석을 위해 기본적으로 Espree 파서를 사용합니다. Typescript 구문 분석을 위해 사용되는 @typescript-eslint/parser를 넣어줬습니다.
  • extends : 확장 설정을 넣어줍니다.

    위에서 설치한 eslint-config-prettier의 설정방법이 8.0.0 버전 이후로 하나로 통합되었습니다.
    참고하여 세팅해주세요.

  • plugins : 사용할 플러그인을 넣어줍니다.
  • ignorePatterns : 파일이나 디렉토리를 제외합니다.
  • env : 프로젝트의 사용 환경을 넣어줍니다. jest 같은 테스트 환경도 넣어줄 수 있습니다.
  • rules : extends와 plugins에 규칙에 대한 세부 설정을 할 수 있습니다. 공식 문서 참조

    0 또는 "off" : 에러 검출 하지 않음
    1 또는 "warn" : 경고
    2 또는 "error" : 에러 표시

.prettierrc

{
	"singleQuote": true,
	"semi": true,
	"useTabs": false,
	"tabWidth": 4,
	"trailingComma": "all",
	"printWidth": 200,
	"endOfLine": "auto",
	"arrowParens": "avoid"
}

공식 문서를 참조해주세용!

4. VS Code 환경설정 해주기 - 저장시 자동 포맷팅

1. 파일 > 기본설정 > 설정으로 들어가주세요!

2. Format On Save 검색 후 체크박스 체크

👍 마무리

이제 코드를 저장하면 자동 정렬이 되어 저장됩니다!

📁 파일구조

참고 사이트

https://velog.io/@kyusung/eslint-config-2#%ED%99%98%EA%B2%BDenv
https://rexiann.github.io/2020/12/13/what-is-eslint.html

profile
4년차 웹 개발자 입니다. 프론트엔드 개발자로 성장 중 입니다.

1개의 댓글

comment-user-thumbnail
2021년 9월 23일

Failed to load plugin 'prettier' declared in '.eslintrc': Cannot find module 'eslint-plugin-prettier'
이런 오류가 납니답

답글 달기