본문 바로가기
  • 바쁜 일상 속 작은 기억
React

[컨벤션 세팅] React TypeScript Eslint+Prettier 세팅하기

by hellomingure 2022. 3. 28.

나 혼자 개발할때는 내가 원하는대로 작업하면 되지만,

회사나 프로젝트 협업 할 때에는 정갈한 코드를 위해 컨벤션을 정해서 작업하는게 좋다.

 

그 작업을 도와주는 툴 중 하나가 ESLint다.

주로 사용하는 Airbnb ESLint 설치를 해보도록 하자.

 


ESLint?

ES는 EcmaScript 즉, 자바스크립트를 의미하고, Lint는 '보푸라기'라는 뜻으로 보푸라기가 많으면 옷이 보기 좋지 않은 것 처럼 코드에서도 이런 보푸라기가 많으면 코드의 가독성이 떨어지고 유지보수하기도 번거로운 경우가 생긴다. 예를들어 들여쓰기를 맞추지 않았다고나, 선언한 변수를 사용하지 않은 경우 등,,,

 

이런 보푸라기를 제거하는 것, 코드의 오류나 버그, 스타일 따위를 점검하는 것을 Lint 혹은 Linter라고 부른다. 

 

ESLint 의 기본 개념

ESLint는 ECMAScript 코드에서 문제점을 검사하고 일부는 더 나은 코드로 정정하는 린트 도구 중 하나다. 코드의 가독성을 높이고 잠재적인 오류와 버그를 제거해 단단한 코드를 만드는 것이 목적이다. 

 

코드에서 검사하는 항목: 

  • 포맷팅 - 일관된 코드 스타일을 유지하도록 하고, 쉽게 읽히는 코드를 만들어준다. (예: 들여쓰기 규칙, 코드라인 최대너비 등)
  • 코드품질 - 어플리케이션의 잠재적인 오류나 버그를 예방하기 위함이다. 사용하지 않는 변수 쓰지않기, 글로벌 스코프 함부로 다루지 않기 등 오류 발생 확률을 줄여준다. 

1. Eslint와 Prettier을 설치한다

yarn add eslint prettier typescript --dev

 

2. eslint에서 TypeScript를 활용하기 위한 플러그인 설치

yarn add @typescript-eslint/eslint-plugin @typescript-eslint/parser --dev

 

3. airbnb 규칙 설정

yarn add eslint-config-airbnb --dev
yarn add eslint-plugin-prettier eslint-config-prettier eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y eslint-plugin-import --dev

 

4. .eslintrc.js 파일 생성

루트폴더에 .eslintrc.js 파일을 생성하고 아래 파일을 붙여넣는다.

옵션 내용은 프로젝트에 맞게 수정해서 쓰면 된다. 

module.exports = {
  // [env] 프로젝트 환경 설정, 브라우저 환경과 ES2021 문법 사용
  env: {
    browser: true,
    es2021: true,
  },
  // [parser] typescript를 parser로 사용하도록 함
  parser: '@typescript-eslint/parser',
  // [plugins] 사용할 eslint 플러그인 설정
  plugins: ['@typescript-eslint', 'prettier'],
  // [extends] 프로젝트에 적용할 eslit 규칙셋
  extends: [
    'airbnb',
    'airbnb/hooks',
    'plugin:import/errors',
    'plugin:import/warnings',
    'plugin:prettier/recommended',
    'plugin:@typescript-eslint/recommended',
    'prettier',
  ],
  // [rules] 상세 규칙
  rules: {
    // var 금지
    'no-var': 'warn',
    // 일치 연산자 사용 필수
    eqeqeq: 'warn',
    // 컴포넌트의 props 검사 비활성화, propstype 사용하지 않아도 경고 띄우지 않음
    'react/prop-types': 0,
    // 불필요한 세미콜론 사용 시 에러 표시
    'no-extra-semi': 'error',
    // jsx 파일 확장자 .jx, .jsx, .ts, .tsx 허용
    'react/jsx-filename-extension': [2, { extensions: ['.js', '.jsx', '.ts', '.tsx'] }],
    // 화살표 함수의 파라미터가 하나일때 괄호 생략
    'arrow-parens': ['warn', 'as-needed'],
    // 사용하지 않는 변수가 있을 때 발생하는 경고 비활성화
    'no-unused-vars': ['off'],
    // 콘솔 사용 시 발생하는 경고 비활성화
    'no-console': ['off'],
    // export문이 하나일 때 default export 사용 권장 경고 비활성화
    'import/prefer-default-export': ['off'],
    // react hooks의 의존성배열이 충분하지 않을 때 경고 표시
    'react-hooks/exhaustive-deps': ['warn'],
    // 컴포넌트 이름은 PascalCase로
    'react/jsx-pascal-case': 'warn',
    // 반복문으로 생성하는 요소에 key 강제
    'react/jsx-key': 'warn',
    // 디버그 허용
    'no-debugger': 'off',
    // [error] Delete `␍` prettier/prettier
    'prettier/prettier': ['error', { endOfLine: 'auto' }],
    // [error] Function component is not a function declaration
    'react/function-component-definition': [2, { namedComponents: ['arrow-function', 'function-declaration'] }],
    'react/react-in-jsx-scope': 0,
    'react/prefer-stateless-function': 0,
    'react/jsx-one-expression-per-line': 0,
    'no-nested-ternary': 0,
    // [error] Curly braces are unnecessary here
    'react/jsx-curly-brace-presence': ['warn', { props: 'always', children: 'always' }],
    // 파일의 경로가 틀렸는지 확인하는 옵션 false
    'import/no-unresolved': ['error', { caseSensitive: false }],
    // props spreading 허용하지 않는 경고 표시
    'react/jsx-props-no-spreading': [1, { custom: 'ignore' }],
    'linebreak-style': 0,
    'import/extensions': 0,
    'no-use-before-define': 0,
    // 테스트 또는 개발환경을 구성 파일에서는 devDependency 사용 허용
    'import/no-extraneous-dependencies': 0,
    'no-shadow': 0,
    'jsx-a11y/no-noninteractive-element-interactions': 0,
  },
  settings: {
    'import/resolver': {
      node: {
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
      },
    },
  },
}

 

5. .prettierrc.js 파일 생성

루트폴더에 .prettierrc.js 파일을 생성하고 아래 파일을 붙여넣는다.

옵션 내용은 프로젝트에 맞게 수정해서 쓰면 된다.

module.exports = {
  // 개행문자 설정
  endOfLine: 'lf',
  // 홑따옴표 사용
  singleQuote: true,
  // 세미콜론 사용 여부
  semi: false,
  // 탭의 사용을 금하고 스페이스바 사용으로 대체
  useTabs: false,
  // 탭의 넓이 2칸
  tabWidth: 2,
  // key: value 뒤에 항상 콤마 붙이기
  trailingComma: 'all',
  // 코드 한 줄의 max lnegth 120
  printWidth: 120,
  // 화살표 함수의 매개변수가 하나일 때 괄호 생략 여부 (생략할 경우 aviod)
  arrowParens: 'always',
}

 

6. vscode 세팅 설정