ReactMasters / study

스터디 기록
1 stars 0 forks source link

11월 4주차 eslint, lint-staged #35

Open JeGwan opened 2 years ago

JeGwan commented 2 years ago

eslint

es + lint es = ecma script lint = 소스코드르 정적 분석하여 프로그램 오류, 버그, 스타일 오류등을 잡아주는 도구

eslint 는 여러명이 함께쓰는 패키지에서 코드 스타일을 통일하고 룰을 강제하게 하는 도구다. 코드적으로는 eslint를 devDependencies로 설치한다.

devDependencies는 개발하는 시점에서는 필요하나 실제로 앱이 돌아갈 때 필요하진 않은 의존성 패키지들을 가리킨다. 즉 우리가 코딩, 컴파일 단계에서 쓰지만, 실제 앱에서 돌아갈 때는 사용하지 않는 패키지들을 개발 의존성으로 설치하면 된다.

설치

yarn add eslint --dev

초기화

yarn run eslint --init

prompt 형으로 실행되어 질문에 답해주면 된다!

# 필자는 이러한 설정으로 써보았어요.

$ /my/project/path/node_modules/.bin/eslint --init
✔ How would you like to use ESLint? · problems
✔ What type of modules does your project use? · esm
✔ Which framework does your project use? · react
✔ Does your project use TypeScript? · No / Yes
✔ Where does your code run? · browser, node
✔ What format do you want your config file to be in? · JavaScript
The config that you've selected requires the following dependencies:

eslint-plugin-react@latest @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest
✔ Would you like to install them now with npm? · No / Yes
Warning: React version not specified in eslint-plugin-react settings. See https://github.com/yannickcr/eslint-plugin-react#configuration .
Successfully created .eslintrc.js file in /my/project/path
✨  Done in 72.41s.

이러면 프로젝트 루트에 .eslintrc.js 파일이 생성된다. 여기서 정의한 extends, plugins, rules 에 따라 검사하게 된다.

특정 디렉토리 무시하기

어떤 디렉토리는 eslint를 무시하고 싶은데 이럴때는 설정파일에 ignorePatterns 옵션으로 직접 파일이나 glob pattern으로 특정 디렉토리와 파일들을 가리키면 된다.

{
  "ignorePatterns": ["temp.js", "**/vendor/*.js"],
  "rules": {
    //...
  }
}

참고 : https://eslint.org/docs/user-guide/configuring/ignoring-code#ignorepatterns-in-config-files

사용법

단일 파일

yarn eslint {filePath}

프로젝트내 모든 파일

yarn eslint .

에디터 도구도 설치하여 코딩 단계에서 linting하기

이것은 lint라는 도구를 설치한 것일 뿐, 에디터에서 코딩하면서 린트가 동작되게 하고 싶으면 에디터 익스텐션으로 eslint를 설치하면 된다.

rules 커스터마이징

끄고 싶은 룰이 있다면 다음처럼 해주면된다.

module.exports = {
  rules: {
    'react/react-in-jsx-scope': 'off',
    '@typescript-eslint/ban-ts-comment': 'off',
  },
}

lint-staged

git hook을 이용하여 커밋할 때 lint 검사를 해보게할 수 있습니다. 이를 위한 도구가 lint-staged 입니다. 한마디로 git의 staging area에 있는 파일 상대로 lint를 해줍니다.

설치

yarn add -D lint-staged

설정 파일

// .lintstagedrc.js
module.exports = {
  // 현재 레포의 모든 js, jsx, ts, tsx 에 대하여
  './**/*.{js,jsx,ts,tsx}': 'eslint',
}

husky 로 pre-commit git hook에 추가

yarn husky add .husky/pre-commit 'yarn lint-staged'