> ## Content Index
> Fetch the complete content index at: https://blog.everyhelloworld.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Node.js Project 설정 가이드 (4) - eslint, prettier 적용
- URL: https://blog.everyhelloworld.com/nodejs-setup-guide-4/
- Published: 2023-07-22T04:49:46.000Z
- Updated: 2024-06-22T14:41:54.000Z
- Author: Dave Lee
- Tags: eslint, typescript, nodejs

eslint는 개발자가 정의한 규칙에 따라 JavaScript나 TypeScript 코드를 분석하고 문제점을 찾아낸다. 이러한 규칙은 코드의 오류, 버그, 스타일 가이드 불일치, 또는 특정 작업 관행에 어긋난 부분을 식별하는 데 사용된다.

eslint는 코드의 문법 오류를 찾아내는 것뿐만 아니라, 프로그래밍 스타일 또는 코드의 가독성을 개선하는 규칙(예: 들여쓰기, 공백, 줄바꿈 규칙 등)에 따라 코드를 검사하고 수정을 제안합니다. 이를 통해 코드의 일관성을 유지하고 잠재적인 오류를 방지할 수 있습니다.

prettier는 문법적인 부분 보다는 코드를 보기 좋고 일관되게 보이는 것에 집중한다. eslint와 역할이 겹치다보니 eslint에서는 아예 prettier의 설정을 가져와 적용할 수 있도록 지원한다.

## 설치

아래와 같이 eslint와 prettier에 관련된 몇가지 패키지를 설치하자.

```
npm install --save-dev eslint prettier eslint-config-prettier eslint-plugin-prettier @typescript-eslint/eslint-plugin @typescript-eslint/parser
```

그리고 프로젝트의 root폴더에 .eslintrc.json 과 .prettierrc 파일을 만들자. eslint:recommended는 eslint에 built-in으로 있는 규칙으로 별도로 뭔가를 설치할 필요는 없다. eslint의 기본 룰이고 일반적인 javascript 오류를 잡아준다.

env는 이 프로젝트가 돌아갈 환경을 eslint에게 알려준다. 가령 node를 쓰는 것을 알려주면 eslint는 console 객체가 있는 것을 알 수 있다. (node를 밝히지 않았을 때 console을 모르는 오류는 js파일에서만 나타났다.)

또한 es2021 등은 어떤 특정 최신 문법을 사용할 수 있는지 힌트를 제공한다. env의 es2020과 parserOptions의 2020은 의미가 좀 다르다. env의 것은 말그대로 2020 수준에서 정의된 global variable을 참조 가능하게 하고, parserOptions의 ecmaVersion은 문법적으로 사용가능한 표현들을 정의한다.

```
{
  "env": {
    "es2020": true, 
    "node": true
  },
  "parser": "@typescript-eslint/parser",
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended"
  ],
  "parserOptions": {
    "ecmaVersion": 2020,
    "sourceType": "module"
  },
  "rules": {
    "prettier/prettier": "error"
  }
}
```

.eslintrc.json

```
{
  "printWidth": 80,     
  "tabWidth": 2,      
  "useTabs": false,   
  "semi": true,       
  "singleQuote": true,    
  "quoteProps": "consistent",
  "trailingComma": "all",
  "bracketSpacing": true,   
  "arrowParens": "always",  
  "endOfLine": "lf"   
}
```

.prettierrc

## 테스트

우리는 지금까지 세미콜론을 일부러 빼먹거나, 문자열에 쌍따옴표를 쓰기도 했다. 다시 바꿀 일이 없는 함수를 let을 이용해 정의하기도 했다. 이를 eslint가 잘 잡아내는지 테스트해보자. 하단 터미널에서 다음과 같이 해보자.

```
➜  my-nodejs-proj npx eslint src/index.ts

/Users/davelee/Documents/projects/javascript-projects/my-nodejs-proj/src/index.ts
  1:42  error  Insert `;`                                       prettier/prettier
  3:13  error  Replace `"hello·world")` with `'hello·world');`  prettier/prettier
  4:11  error  Replace `"dave");` with `'dave');⏎`              prettier/prettier

✖ 3 problems (3 errors, 0 warnings)
  3 errors and 0 warnings potentially fixable with the `--fix` option.

➜  my-nodejs-proj 
```

수정해야 할 부분을 잘 알려준다. 

만약 이 스텝이 잘 진행되지 않았다면 다음 스텝으로 넘어가지 말고 여기서 꼭 해결하고 넘어가야 한다. 익스텐션을 설치하고, workspace설정을 한 다음 안되는 이유를 찾기도 하는데 어디 딱히 에러가 뜨는 것이 아니라서 찾기가 힘들다. 꼭 이 스텝에서 원하는 결과를 보고 다음으로 넘어가자.

## 익스텐션 설치

그런데 이것으로는 좀 부족한 것 같다. 에디터에서 우리가 실수할 때마다 밑줄도 그어주고, 저장할 때 필요한 부분은 자동으로 수정해주었으면 좋겠다. 

우리가 cli 환경에서 하는 것 말고 vscode상에서 어떤 추가 기능을 원한다면 이는 익스텐션으로 해결해야 한다.

좌측 extension 탭을 연 다음 `eslint`를 검색해보자. 그러면 마이크로소프트가 개발한 몇천만명이 다운로드 받은 익스텐션이 있을 것이다. 이를 설치하자.

![](https://blog.everyhelloworld.com/content/images/2023/07/image-1.png)

이를 설치하고 나면 다음과 같이 화면에 표시된다. 이제 실수를 하면 바로바로 눈에 보이게 되었다.

![](https://blog.everyhelloworld.com/content/images/2023/07/image-3.png)

## 저장시 자동 적용

아직 저장시 자동으로 오류를 수정해 주지는 않는다.

cmd+, 또는 메뉴에서 Code - settings - settings 로 환경설정창을 열자.

여기서 이 `workspace`만을 위한 설정으로 전환하자. 개인적으로는 이것을 선호한다. 개발을 하다보면 프로젝트별로 다양한 환경을 설정해야할 필요가 있다. 심지어 다른 언어로 개발을 해야할 수도 있다. 그래서 설정도 workspace별로 하고, npm install -g도 최대한 지양하자.

![](https://blog.everyhelloworld.com/content/images/2023/07/image-4.png)

그리고 이 설정을 텍스트로 변경할 수 있는 창을 열자. 우상단에 종이 뒤집는 아이콘을 누르면 된다. (그러면 사실상 root/.vscode/setting.json을 수정하는 것이 된다.)

![](https://blog.everyhelloworld.com/content/images/2023/07/image-5.png)

그리고 다음 설정을 추가하자.

```
{
    "editor.tabSize": 2,
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "dbaeumer.vscode-eslint",
    "eslint.format.enable": true,
    "javascript.format.enable": false,
    "workbench.editor.labelFormat": "short",
    "typescript.suggest.paths": true,
}
```

이제 index.ts에서 cmd+s로 저장을 해보자. 그러면 아래와 같이 규칙에 맞게 내용이 수정된 것을 볼 수 있다.

![](https://blog.everyhelloworld.com/content/images/2023/07/image-6.png)