Skip to main content

React, Typescript 프로젝트에 eslint, prettier 적용 후 자동화하기


React, Typescript 프로젝트에 코드 품질포맷 검사를 하고, 이를 자동화하는 방법이다.

  • eslint : 코드 품질 검사
  • prettier : 코드 포맷 검사
  • lint-staged : staged 파일에서만 특정 명령어가 실행되도록 함
  • husky : git hook 사용하게 함 (pre-commit을 이용하여 커밋 할때 특정 명령어 실행 가능)

목적: 커밋할 경우, staged 파일들에 대해서 eslint, prettier를 실행하고 문제가 발생했을 경우 커밋 취소되도록 설정하기



1. CRA, Typescript 생성

아래 명령어를 입력하여 typescript 템플릿으로 React 앱을 생성해준다.

npx create-react-app my-app --template typescript


2. eslint 설치 및 설정

eslint 설치하기

npm install -D eslint

아래 명령어를 입력하여 초기 설정을 해준다.

npx eslint --init

How would you like to use ESLint?

To check syntax and find problems

What type of modules does your project use?

JavaScript modules (import/export)

Which framework does your project use?

React

Does your project use TypeScript?

Yes

Where does your code run?

Browser

What format do you want your config file to be in?

JSON

Would you like to install them now with npm?

No


설정이 끝나면 .eslintrc.json 파일이 만들어지게 된다.


추가로 아래 패키지들을 설치해준다.

npm install -D eslint-plugin-react@latest @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest
npm install -D eslint-plugin-import @typescript-eslint/parser eslint-import-resolver-typescript

.eslintrc.json에서 아래 항목들은 추가해주고, 규칙을 설정한다. (eslint 규칙)

{
"env": {
"browser": true,
"es2021": true,
"jest": true // 'jest'를 사용한다면 추가
},
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended",
"prettier" // 'prettier' 추가
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": ["react", "react-hooks", "@typescript-eslint", "prettier"], // 'react-hooks', 'prettier' 추가
"rules": {
// 원하는 eslint 규칙들 추가
"react/react-in-jsx-scope": "off", // 리액트를 명시적으로 import 하지 않아도 됨
"camelcase": "error", // 카멜 케이스 표기가 아니면 에러
"spaced-comment": "error", // 주석표기 뒤에 띄어쓰기가 없으면 에러
"quotes": ["error", "single"], // 작은따옴표가 아니면 에러
"no-duplicate-imports": "error" // 같은 모듈이 두 번 이상 import 되면 에러
},
// 'settings' 추가
"settings": {
"import/resolver": {
"typescript": {}
},
"react": {
"version": "detect"
}
}
}


3. prettier 설치 및 설정

prettier 및 플러그인을 설치하기

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

.prettierrc.json 파일을 디렉토리의 최상단에 생성해주고 원하는 옵션을 작성해준다. (prettier 옵션)

{
"semi": true, // 세미콜론 사용 여부
"tabWidth": 2, // 들여쓰기 폭
"printWidth": 100, // 코드 최대 길이 (초과되면 줄바꿈)
"singleQuote": true, // 작은 따옴표 적용
"trailingComma": "all", // 배열이나 오브젝트 마지막에 쉼표 적용
"jsxSingleQuote": true, // jsx에서 작은 따옴표 적용
"bracketSpacing": true, // 중괄호에서 처음과 끝에 띄어쓰기 적용
"singleAttributePerLine": true // props를 한 줄에 하나씩 적용
}


4. ignore 파일 생성

디렉토리의 최상단에 .eslintignore, .prettierignore 파일을 추가해서, 특정 폴더 및 파일에 대해서 eslint와 prettier 설정이 무시되도록 할 수 있다.


.eslintignore.prettierignore

/src/react-app-env.d.ts


5. lint script 추가

복잡한 명령어를 간편하게 실행할 수 있도록 스크립트 추가 (package.json > script 에서 수정 가능)

npm set-script lint "eslint --fix **/*.{js,jsx,ts,tsx} && prettier --write **/*.{js,jsx,ts,tsx,json,css,scss,md}"

아래 명령어 입력하면 eslint --fixprettier --write가 순차적으로 실행되면서 자동으로 코드가 수정 되고, 자동으로 수정되지 않을 경우 오류 메세지를 출력

npm run lint


6. staged 파일만 검사하기

매번 모든 파일을 검사하는것은 비효율적이므로, staged 파일들만 검사하도록 lint-staged 설치하기

npm install -D lint-staged

package.json에 아래 코드 추가하기

(만약 검사만 하는것이 아닌 자동으로 수정하기를 원하면 eslint --fix, prettier --write로 입력하면 된다.)

  "lint-staged": {
"*.{js,jsx,ts,tsx}": [
"eslint",
"prettier --check"
],
"*.{css,scss,md,json}": [
"prettier --check"
]
},

아래 명령어를 입력하면 staged된 파일들만 eslint, prettier --check를 실행한다.

npx lint-staged

7. 자동화

huskypre-commit을 사용하면 커밋을 할 때 특정 명령어가 먼저 실행 되도록 할 수 있으며, 오류가 발생했을 경우 커밋 과정이 자동으로 중단이 된다.


아래 명령어들을 입력하여 husky 설치 및 설정하기

npm install -D husky
npm set-script prepare "husky install"
npm run prepare

커밋할 때 먼저 실행될 명령어 추가 (.husky/pre-commit에서 수정 가능)

npx husky add .husky/pre-commit "npx lint-staged"



이제 커밋할 경우 자동으로 eslint와 prettier로 검사가 실행된다.

오류가 발생한다면 npm run lint직접 해결 한 뒤 다시 커밋해주면 된다.



기타. vscode에서 저장시 eslint, prettier 적용

ctrl+shift+p > settings.json에 들어가서 아래 코드 추가

  "[typescriptreact]": {
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
},
"eslint.enable": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true

이제 vscode에서 저장할때마다 eslint와 prettier가 자동으로 적용된다.



참고자료