치춘짱베리굿나이스

eslint, prettier 설정 본문

ClientSide/기타

eslint, prettier 설정

치춘 2022. 4. 15. 14:36

eslint

Javascript & JSX의 정적 분석 도구

Javascript는 코드 실행 후에 에러를 파악할 수 있는데 (동적 분석), 이를 실행 없이도 코드 내에서 바로 찾을 수 있도록 (정적 분석) 도와주는 도구이다

eslint는 코드 그 자체를 분석해 문법 오류나 안티 패턴 (패턴을 지키지 않은 부분) 을 찾아주어 일관된 코드 스타일을 유지하게 해 준다

설치하기

npm install eslint -D

-D 옵션은 개발 단계에서만 해당 도구를 사용하겠다는 의미이다 (배포 단계에서는 적용되지 않는다는 뜻)

설정하기

npx eslint --init

Javascript에서 React를 이용하여 개발하고자 한다면 다음과 같이 설정한다

세팅이 완료되면 eslintrc.js 파일이 생성된다 (json 형식을 선택했다면 .eslintrc.json, yaml 형식을 선택했다면 .eslintrc.yaml)

설정별 의미

  1. problems - ESLint로 어떠한 문제점을 발견할 것인지에 대한 질문
    • How would you like to use ESLint?
      • To check syntax only => it helps you correct your syntax and make sure it conform to standard.
      • To check syntax and find problems => to help you check for syntax correctness and also help to find any problems in your code base
      • To check syntax, find problems, and enforce code style_ => to help you check for syntax, find problem and enforce style, enforcing style means to conforms to a particular coding standard such as Airbnb, Google and other Standard coding style. But I always go for the last option the one with syntax, find problems and enforce code style
      코드의 문제점과 안티 패턴을 찾아주도록 두 번째 답안으로 세팅하였다
  2. esm - Javascript 모듈 / CommonJS 모듈 중 어떤 것을 사용할 지에 대한 질문
    • What type of modules does your project use?
      • Javascript module (import/export) => if your project has babel installed then you definitely need to choose this option. If you are working on a project such as React, Vue, Angular e.t.c they all use babel so you need choose this option.
      • CommonJS (require/exports) => this option is meant for commonJS that has nothing to do with babel, maybe your nodejs project and any other javascript project
      Javascript와 Babel을 사용할 수 있도록 (React, Vue, Angular은 모두 Babel을 쓰므로) 첫 번째 답안으로 세팅하였다
    • (Babel: ES6 자바스크립트 코드를 ES5 이하를 지원하는 브라우저에서도 돌아갈 수 있게 컴파일해 주는 컴파일러)
  3. react - 어떤 웹 프레임워크를 사용할 지에 대한 질문
    • Which framework does your project use?
      • React => if you are using react in/for your project then this option is for you
      • Vue => if you are using Vue in/for your project then this option is for you
      • None of these => if you are using neither React or Vue in your project choose this option
      리액트를 사용하여 작업할 것이므로 첫 번째 답안 세팅
  4. No - Typescript 사용 유무에 대한 질문
  5. browser - 어떠한 환경에서 코드가 작동할 것인지에 대한 질문 (브라우저 / Node.js)
    • Where does your code run?
      • Browser => if your project runs on browser e.g React, Angular, Vue e.t.c then go for this option
      • Node => if your project is a node based then gladly choose this option
      프론트엔드는 브라우저에서 코드가 구동되고, 백엔드는 주로 Node에서 코드가 구동되므로 첫 번째 답안 세팅
  6. Javascript - eslint 설정 파일이 어떠한 형식으로 저장되는 것을 원하는지에 대한 질문 (Javascript / JSON / YAML)
    • What format do you want your config file to be in?
      • Javascript => whether you want your eslint config file to be in .js file
      • YAML => whether you want your eslint config file to be in .yaml file
      • JSON => whether you want your eslint config file to be in .json file you can choose any option in this section

eslint의 vscode 확장

위의 확장을 설치하면, 프로젝트의 루트 폴더에서 eslint 세팅을 읽어와 자동으로 에러 검출을 시작한다

예시 이미지에서의 에러는 React 모듈 불러오기를 안 해서 JSX 형식을 쓸 수가 없다고 안내문을 뱉는 모습이다

컴파일은 되지만, 왠만해선 지켜 주는 것이 좋다

eslint 예외 설정

최상단에 import { React } from "react" 라인을 추가하면 위의 오류가 사라진다

또는 해당 에러를 뱉는 라인에 마우스를 올려 에러명을 확인한 후, eslintrc.js의 rules에 해당 에러를 무시하도록 추가하면 예외로 적용되어 에러를 잡지 않는다

혹시나 eslint가 적용되지 않았으면 하는 파일이 있다면 .eslintignore 파일을 생성하여 gitignore처럼 파일 및 폴더 목록을 적어넣거나, eslintrc.js의 ignorePatterns에 파일명을 경로와 함께 추가하면 된다

Prettier

코드 포매터

자바스크립트, HTML, css 등의 코드를 지정한 형식으로 예쁘게 변환해주며, 업계 표준급으로 사용되는 포매터이다

기본 설정이 어느정도 되어있어 사용자 설정을 할 부분이 크게 없다는 점이 매력적이다

널리 사용되는 norminette의 자동 변환 도구라고 생각하면 쉽다

설치하기

npm install prettier -D -E

-E 옵션은 npm 설치 시 버전을 ^, ~와 같은 기호로 표기하지 않고, 정확한 버전으로 설치한다

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

eslint-plugin-prettier는 prettier 포맷 오류를 eslint에서 오류로 출력해준다

eslint-config-prettier는 eslint와 prettier간 설정 충돌하는 부분을 비활성화한다

설정하기

module.exports = {
    tabWidth: 2,
    useTabs: false,
    semi: true,
    singleQuote: true,
    trailingComma: 'all',
    printWidth: 80,
    arrowParens: 'avoid',
    endOfLine: 'auto',
  };

프로젝트의 루트 폴더에 .prettierrc.js 파일을 만들고, 위의 내용을 적는다

module.exports = {
  env: {
    browser: true,
    node: true,
    es2021: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:prettier/recommended',
    'plugin:react/recommended',
  ],
  ignorePatterns: ['node_modules/', 'reportWebVitals.js'],
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 12,
    sourceType: 'module',
  },
  plugins: ['react', 'prettier'],
  rules: {
    'prettier/prettier': 'error',
  },
};

프로젝트 루트 폴더의 .eslintrc.js를 위와 같이 수정한다

  • 브라우저, node, es2021 환경을 모두 적용한다
  • eslint 확장으로 react와 prettier 관련 플러그인을 사용한다
  • node_modules 폴더와 reportWebVitals.js 파일은 eslint를 적용하지 않는다
  • prettier 오류도 eslint에서 띄운다

설정별 의미

  • tabWidth: 2
  • 탭 한 칸의 간격을 스페이스바 2개로 설정
  • useTabs: false
  • Tab (/t) 을 사용하지 않고 스페이스바를 사용
  • semi: true
  • 각 코드라인의 맨 끝에 세미콜론 추가
  • singleQuote: true
  • 문자열에 홑따옴표 사용 (쌍따옴표 사용하지 않음)
  • trailingComma: 'all'
  • 객체 (Object), 배열 (Array) 의 원소 뒤에 무조건 콤마 추가 (마지막 원소에도 콤마 붙음)
  • printWidth: 80
    코드 한 줄의 최대 길이를 80자로 설정
  • arrowParens: 'avoid'
    Arrow 함수에서 하나의 매개변수를 받을때는 괄호를 생략
  • endOfLine: 'auto'
  • EOF 자동 추가

prettier의 vscode 확장

세팅이 완료되었다면, Vscode의 ESLint 확장에서 prettier 오류까지 출력하는 것을 볼 수 있다

 

저장할 때마다 자동 포매팅 설정하기

VSCode의 Prettier 확장을 설치한 상태라면, 파일을 저장할 때마다 prettierrc.js에 적용된 내용대로 코드를 포매팅한다

 

두 설정을 위와 같이 맞춘다


참고자료

Comments