vscode에서 lint, prettier, settings.json 설정

노요셉·2021년 1월 27일
5

eslint + prettier

같은 코드 베이스로 협업하기 위해 사용합니다.

다음 패키지들을 설치합니다.

# ESLint 관련 패키지
npm i -D eslint eslint-plugin-import

# Typescript ESLint 패키지
npm i -D @typescript-eslint/eslint-plugin @typescript-eslint/parser

# Prettier 관련 패키지
npm i -D prettier eslint-config-prettier eslint-plugin-prettier

저희 airbnb-base를 설치하진 않았어요.
npm i -D eslint-config-airbnb-base

eslint를 관리해줄 설정파일을 만듭니다.

프로젝트 루트 디렉토리에 .eslintrc.js 만듭니다. 공식사이트 에 나온대로 설정파일 만드는 방법은 다양해요.

.eslintrc.js

module.exports = {
  parser: '@typescript-eslint/parser',
  extends: [
    'plugin:@typescript-eslint/recommended', // 타입스크립트 추천 룰셋
    'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
    'plugin:prettier/recommended',// eslint의 포매팅 기능을 prettier로 사용함. 항상 마지막에 세팅 되어야 함. - eslint-config-prettier
  ],
  parserOptions: {
    ecmaVersion: 2018, // 최신 문법 지원
    sourceType: 'module', // 모듈 시스템 사용시
  },
  rules: {
    // indent: ['error', 2], 누구는 eslint-config-prettier 충돌을 막는다는데 indent의 경우는 그냥 rule를 꺼버리는게 나아요. 계속 충돌되요 fix eslint <-> fix prettier
    // extends에서 적용한 룰셋을 덮어씌울 수 있습니다.
    // '@typescript-eslint/explicit-function-return-type': 'off',
  },
  settings: {},
};

포매팅을 해줄 prettier 설정파일을 만듭니다.

프로젝트 루트 디렉토리에서 .prettierrc 생성합니다.

{
  "singleQuote": true,
  "trailingComma": "all",
  "bracketSpacing": false,
  "printWidth": 120,
  "tabWidth": 2,
  "semi": true,
  "arrowParens": "avoid",
  "endOfLine": "lf"
}

각 용어들은 뭘 뜻하나? Prettier 공식사이트에 나와있습니다.

vscode에서 저장시 eslint, prettier 동작하게 settings.json를 생성해줍니다.

저희팀은 vscode를 쓰고있어요. husky를 이용해서 commit할때 할 수도 있지만 저장할때마다 eslint, prettier 동작하게 하고싶어요.

저 같은 경우 vscode 에디터에 개인 설정이 있을 수 있잖아요 cmd + shift + p로 명령파레트를 사용할 수 있는데, 맨 위에 있는거에 개인 설정을 추가할 수 있죠.

프로젝트 루트 디렉토리에 .vscode 이름으로 디렉토리 생성해주시고 settings.json을 추가해주세요. 사용하시는 개인 설정과 merge되어 반영되요.

우선순위는 .vscode settings.json > settings.json > defaultSetting.json( 건드리지 않아요)

{
  "editor.formatOnSave": false,     // 저장시 format
  "editor.codeActionsOnSave": {
    // For ESLint
    "source.fixAll.eslint": true,
  },
    // Enable per-language
  "[typescript]": {
    // "editor.formatOnSave": true,
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[json]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    // "editor.formatOnSave": true,
  },  
  "workbench.settings.useSplitJSON": true // 요거 넣어줘야 설정이 merge된대요.
}

마지막으로 ESlint, Prettier extension을 설치해줍니다.


이렇게 되면 팀내에서 같은 코드베이스로 작업할 수 있습니다.
진짜 문제는 webstorm 유저인데... 설정을 실패해서 다음에 성공하면 포스트할 생각입니다.

prettier 옵션 적용해보기

Prettier Option : Prettier에 사용할 옵션들이 나와있음.
Prettier : Prettier 옵션을 적용해보면서 어떤 옵션들이 적용되는지 확인해볼 수 있는 playground GUI
예를 들어, --print-width가 잘 동작하는지 보려면 좌측에 설정을 바꿔보면 된다.
editor 화면이 두개 나오는데 왼쪽에 입력하고 오른쪽에는 prettier가 적용된 코드들이 보이게 된다.

참고로 vscode editor 기본 포맷팅 설정도 있어요.

.editorconfig 같은 파일로 사용하는 경우도 있는데
prettier를 쓰면 우선순위가 vscode editor config보다 높아요.
https://prettier.io/docs/en/options.html 여기에 나옵니다.

문제의 html... html의 경우 prettier 동작하지 않는다고 해서 vscode 기본 formatter를 쓰도록 해요
.vscode/settings.json

{
  ...
  "prettier.disableLanguages": ["html"],
  "[html]": { 
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "vscode.html-language-features" 
  },
}

참조:
https://www.npmjs.com/package/eslint-plugin-prettier

https://dev.to/bhargavmantha/the-secret-to-configuring-eslint-prettier-prettier-eslint-plugin-in-vscode-for-angular-ts-and-js-project-51la

https://iamsjy17.github.io/angular/2020/04/18/angular_eslint_prettier.html

https://medium.com/@kelmants/best-practices-angular-with-eslint-prettier-husky-50d12067831e

https://interacting.tistory.com/143

lint, prettier 설명

https://jeonghwan-kim.github.io/series/2019/12/30/frontend-dev-env-lint.html

ESLint: ECMAScript 코드를 검사하고 코드를 정정하는데 도움을 주는 도구 중 하나

  • 포맷팅
  • 코드 품질 적용

eslint 설치
npm i -D eslint

환경설정 파일을 프로젝트 최상단에 생성함. .eslintrc.js
module.exports = {}

ESLint로 코드 검사
npx eslint app.js

ESLint는 검사 규칙을 미리 정해 두고 문서의 Rules 메뉴에서 규칙 목록을 확인할 수 있음.

.eslintrc.js

module.exports = {
  rules: {
    "rule이름": "rule설정값",
  }
}

rule 설정값 "off"는 0, "warn"은 1 "error"는 2

ESLint를 실행하면 규칙에 어긋난 코드 위치, 위반한 규칙명을 알려줍니다.

자동으로 수정할 수 있는 규칙

미리 정해 놓은 규칙

흔히 많이 쓰는 규칙 모음을 설정함으로써 구체적으로 일일히 규칙을 찾아서 설정하는 수고를 덜 수 있음.

.eslintrc.js

module.exports ={
  extends: [
    "eslint:recommended", // 미리 설정된 규칙 세트를 사용한다.
  ]
}

이어서 작성할 것..
좋아 그런데, vscode editor.formatOnSave는?
에디터 자체 코드 포맷팅하고는 우선순위가 어떻게 되나?


https://glebbahmutov.com/blog/configure-prettier-in-vscode/

참고: https://feynubrick.github.io/2019/05/20/eslint-prettier.html
https://glebbahmutov.com/blog/configure-prettier-in-vscode/


lint 옵션

error Parsing error: 'import' and 'export' may appear only with 'sourceType: module'

.eslintrc.json

    "parserOptions": {
        "sourceType": "module"
    }

https://github.com/AtomLinter/linter-eslint/issues/462

Parsing error: Unexpected character '@'

.eslintrc.json
npm i -D babel-eslint

    "parser": "babel-eslint"

https://stackoverflow.com/questions/40678196/eslint-unexpected-character-for-js-decorators

51:1 error Parsing error: Using the export keyword between a decorator and a class is not allowed. Please use export @dec class instead.


angular v9 tslint to eslint

tslint에 rule를 많이 커스텀해놨으면 사용할 수 있지만 비추

npm i -D tslint@5.18
npx tslint-to-eslint-config 
npm i -D eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-config-prettier eslint-plugin-rxjs  
npm i eslint-plugin-import @typescript-eslint/eslint-plugin-tslint @typescript-eslint/parser

참조 :
https://ngohungphuc.wordpress.com/2020/04/19/migrate-from-tslint-to-eslint-with-angular-9/
https://medium.com/@intelino/angular-migration-from-tslint-to-eslint-f932ed8d0ddd

profile
서로 아는 것들을 공유해요~

0개의 댓글