ETC

ESLint와 Prettier (2) - VSCode에 ESLint와 Prettier설치

범데이 2022. 10. 17. 22:21

1. 개요

지난 포스팅에서는 ESLint와 Prettier의 특성과 차이점에 대해 살펴보았다. 

이번 포스팅에서는 VSCode에서 ESLint와 Prettier를 설정하는 방법을 살펴보고자 한다.

 

 

 

2. VSCode로 ESLint 및 Prettier 설정하기

코드 편집기에 적합한 확장/플러그인을 설치해야 한다. VSCode의 경우 ESLint및 Prettier를 설치한다.

이러한 플로그인에는 각각 수백만 건의 다운로드가 있으므로 VSCode 확장 마켓플레이스에서 쉽게 찾을 수 있다. 이들을 설치했으면 적절한 사용을 위해 각각을 구성할 준비가 된 것이다.

 

ESLint와 Prettier 설정

앞서 언급했듯이 ESLint와 Prettier는 주의해서 설정하지 않으면 서로 충돌한다. 다행히도 이것은 널리 알려진 문제이기 때문에 이 문제를 정확히 해결하기 위해 만들어진 패키지가 있다. 우리는 두 개의 다른 패키지를 설치할 것이다. eslint-config-prettier는 Prettier와 충돌할 수 있는 모든 ESLint규칙을 제외하고 eslint-plugin-prettier는 Prettier 규칙을 ESLint 규칙에 통합한다.

이렇게 하면 서로 충돌하는 두 가지 규칙이 없어진다.

npm install --save-dev eslint-config-prettier eslint-plugin-prettier

(참고: --save-dev 명령어에대해 모른다면 : 이 포스팅을 참고하자.)

 

 

이제 해당 패키지를 성공적으로 설치했으므로 프로젝트 내에서 ESLint를 초기화하는 몇 가지 명령을 실행해야 한다.

eslint --init
✔ How would you like to use ESLint? · style
✔ What type of modules does your project use? · esm
✔ Which framework does your project use? · none
✔ Does your project use TypeScript? · No / Yes
✔ Where does your code run? · browser
✔ How would you like to define a style for your project? · guide
✔ Which style guide do you want to follow? · airbnb
✔ What format do you want your config file to be in? · JSON
Checking peerDependencies of eslint-config-airbnb-base@latest
Local ESLint installation not found.
The config that you've selected requires the following dependencies:

eslint-config-airbnb-base@latest eslint@^5.16.0 || ^6.8.0 || ^7.2.0 eslint-plugin-import@^2.21.2
✔ Would you like to install them now with npm? · No / Yes
Installing eslint-config-airbnb-base@latest, eslint@^5.16.0 || ^6.8.0 || ^7.2.0, eslint-plugin-import@^2.21.2
npm WARN eslint-plugin-prettier@3.1.4 requires a peer of prettier@>=1.13.0 but none is installed. You must install peer dependencies yourself.
npm WARN eslint-prettier-blogpost@1.0.0 No repository field.

+ eslint-plugin-import@2.22.0
+ eslint-config-airbnb-base@14.2.0
+ eslint@7.6.0
added 171 packages from 100 contributors and audited 176 packages in 10.789s

24 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

위에서 설명한 것처럼 eslint --init 명령을 실행하면 린터의 구성을 결정하기 위한 질문이 표시된다.

작업 중인 프로젝트를 기반으로 이러한 질문에 답하기만 하면 된다. 여기서 주의할 점은 “어떤 스타일 가이드를 따르고 싶습니까?” 라는 질문이다. JavaScript표준 스타일 가이드, Airbnb 스타일 가이드, Google 스타일 가이드 등 다양한 스타일 가이드가 있다. 이것은 많은 개발자들이 선택하는 매우 인기 있는 가이드이다.

(나와 내 팀에 고유한 스타일 가이드 세트가 있는 경우 기존 스타일 가이드를 선택할 필요가 없다.)

 

설정이 성공하면 구성 파일을 선택한 형식에 따라 eslintrc.{js/json/yaml] 파일이 표시된다.

Prettier를 ESLint로 실행하려면 구성 파일이 다음과 같아야 한다.

{
    "env": {
        "browser": true,
        "es2020": true
    },
    "extends": [
        "airbnb-base",
        "prettier"
    ],
    "plugins": ["prettier"],
    "parserOptions": {
        "ecmaVersion": 11,
        "sourceType": "module"
    },
    "rules": {
        "prettier/prettier": ["error"]
    }
}

(참고: linter가 무시할 파일/디렉토리를 .eslintignore(.gitignore 파일과 매우 유사한 개념) 라는 파일에 포함할 수 있다.)

 

 

이제 마지막 단계만 남았다. 로컬에서 Prettier를 설정하고 코드 형식을 지정하는 방법을 Prettier에 알려야 한다.

# install prettier as local devDependency
npm install --save-dev prettier

로컬 devDependency로 Prettier를 설치했어야 한다. 이제 Prettier에 대한 구성 파일을 만들고 코드 형식을 지정하는 방법을 알려야 한다.

# in your project root directory
touch .prettierrc

 

코드 편집기에서 .prettierrc를 열고 Prettier에 대한 구성을 설정한다.

{
    "semi": true,
    "trailingComma": "all",
    "singleQuote": true,
    "printWidth": 70
}

이것은 단순히 가능한 구성이지만 Prettier 공식 홈페이지(https://prettier.io/docs/en/configuration.html)에서 다른 옵션을 자유롭게 살펴볼 수 있다.

 

VS Code 구성

따라서 여전히 ESLint과 Prettier를 실제로 어떻게 사용할 것인지 자문할 수 있다. 그것들은 자동으로 작동할 것인가? 우리가 이해해야 할 한 가지는 ESLint 규칙으로 실행되도록 Prettier를 설정하는 방식이다.

 eslint-config-prettier를 통해 충돌하는 모든 규칙을 제외하고 eslint-plugin-prettier를 통해 Prettier를 ESLint 규칙으로 통합했다. 결과적으로 lint와 코드 formatting을 모두 원하는 결과를 얻으려면 ESLint만 실행하면 된다.

 ESLint는 주로 두 가지 다른 방법으로 실행할 수 있다. ESLint CLI를 사용하여 linter(eslint index.js 형식)를 수동으로 실행하거나 저장 시 코드를 자동으로 형식화하는 방식으로 VS Code 구성을 설정할 수 있다.

 

 명확히 하자면, ESLint는 CLI를 통해 수동으로 실행하지 않더라도 가능한 버그와 오류에 대해 코드를 검사하지만 VS Code 구성이 그렇게 설정되지 않은 경우 코드를 자동으로 포맷하지 않는다. 저장 시 코드 형식이 자동으로 지정되는 것을 좋아하므로 정확히 그렇게 하기 위해 VS Code 구성을 다음과 같이 조정할 수 있다.

// VS Code Settings JSON
// Set the default
"editor.formatOnSave": false,
// Enable per-language
"[javascript]": {
    "editor.formatOnSave": true
}

이 설정을 사용하면 파일을 저장할 때 코드가 자동으로 형식이 지정되는 것을 볼 수 있다.

이제 ESLint와 Prettier가 VS Code와 함께 훌륭하게 작동한다.

 

 


#References

https://www.jeffyang.io/blog/eslint-prettier-vscode

반응형