개요
혼자 프로젝트를 진행하거나 다른 사람들과 프로젝트를 진행할 때 이전에 작성했던 코드나 다른 사람이 작성한 코드에서 정상적으로 작동했던 코드인데 오류가 나는 경우가 있습니다. 이럴 때 "왜 잘 작동했던 코드인데 오류가 나지?"라는 생각이 드는데요. 여기에는 여러 가지 이유가 있을 수 있지만 이유 중 한 가지로 지금 코드를 작성하는 방식과 이전에 또는 다른 사람이 코드를 작성하는 방식이 달라서 이러한 오류가 발생할 수 있습니다.
오늘 포스팅할 ESLint와 Prettier는 이러한 부분에서 생기는 문제를 해결할 수 있는 개발 도구입니다.
ESLint?
ESLint에 대해 설명하려면 "lint"라는 단어를 살펴보아야 합니다. lint를 한국어로 그대로 해석하자면 보풀이라는 뜻을 가지고 있습니다. 평소에 옷을 입을 때 옷에 보풀이 있으면 자기 자신이 보거나 다른 사람이 봤을 때에도 보기 좋지 않을 수 있습니다. 또한 옷에 보풀이 있다 의식하면 계속 거슬리는 경우가 생길 수도 있습니다.
코드에서도 마찬가지입니다. 들여쓰기가 되지 않았다던가, 변수를 선언해 놓고 쓰지 않았다던가, 사용하지 않아야 할 라이브러리나 변수를 사용하고 있다던가 하는 경우를 예시로 들 수 있습니다.
이러한 보풀이 쌓이고 쌓이면 처음에 샀던 옷의 모양을 유지할 가능성이 적습니다. 코드도 열심히 작성해도 이러한 보풀이 쌓인 코드는 가독성이 떨어지고 유지보수 측면에서도 좋지 않습니다.
그러기 때문에 이러한 보풀을 제거해줘야하고 lint가 이러한 역할을 해줍니다.
오늘 포스팅할 ESLint는 EcmaSCript(javascript)와 lint를 합친 것으로 lint의 한 종류입니다.
본문
오늘 포스팅에서는 이러한 ESLint를 typescript환경에서 사용할 수 있도록 적용하는 부분을 작성해보고자 합니다.
※개발 환경
- vscode
- react
- typescript
- pnpm
ESLint를 사용하기 위해서는 먼저 필요한 패키지를 설치해야 합니다. typescript환경에서 사용할거라 typescript 관련 라이브러리들로 설치해 줍니다.
이렇게 설치가 완료되었으면 이제 설치된 eslint를 프로젝트에 적용시켜줘야 합니다. 적용할 프로젝트에 들어가서 다음과 같이 명령어를 실행시켜 주면 여러 가지 질문들이 나오는데 프로젝트에 맞게 설정해주고 나면 아래 사진과 같이 .eslintrc.cjs파일이 생기면서 프로젝트에 적용이 됩니다.
pnpm eslint --init
정상적으로 파일이 생성되었다면. eslintrc.cjs파일을 열어주면 다음과 같은 화면이 띄워집니다.
여기서 "rules" 부분에 규칙들을 설정해 주면 프로젝트에 대해 코드 규칙을 설정할 수 있습니다.
코드 규칙에는 많은 종류가 있고, 제가 사용하는 규칙 몇 가지에 대해 작성해보았습니다.
규칙을 작성할 때 주의해야할 점으로 typescript 사용 시에는 아래와 같이 typescript에 맞는 규칙들을 추가해 줘야 typescript 환경에서 정상적으로 작동됩니다.
// eslintrc.cjs
rules: {
// 사용자 정의 규칙
"react-refresh/only-export-components": [
"warn",
{ allowConstantExport: true }, // React 컴포넌트만 내보내도록 하는 규칙
],
"@typescript-eslint/explicit-module-boundary-types": "off", // 함수 반환 타입 명시 규칙 해제
"@typescript-eslint/no-unused-vars": "error", // 사용하지 않는 변수 사용시 에러 규칙
"@typescript-eslint/no-empty-interface": "error", // 빈 인터페이스 사용 시 에러 규칙
"@typescript-eslint/no-var-requires": "off", // require 사용 규칙 해제
"@typescript-eslint/ban-types": "off", // 특정 타입 사용 제한 규칙 해제
"@typescript-eslint/no-non-null-assertion": "off", // 비-널 단언 연산자 사용 규칙 해제
"@typescript-eslint/no-empty-function": "off", // 빈 함수 규칙 해제
"@typescript-eslint/no-namespace": "off", // 네임스페이스 사용 규칙 해제
"@typescript-eslint/ban-ts-comment": "off", // @ts-ignore 사용 규칙 해제
},
또한 코드 포맷팅을 지정하기 위해 .prettierc 파일을 생성해 prettier도 적용해 주었습니다.
아래는 작성한 .prettierc 파일입니다.
// .prettierc
{
"singleQuote": true,
"parser": "typescript",
"semi": true,
"useTabs": false,
"tabWidth": 2,
"printWidth": 120,
"arrowParens": "always"
}