티스토리 뷰

728x90
SMALL

협업세팅을 팀원과 나 둘다 제대로 해본적이 없다보니 대충 책에서 본 코드를 복사붙여넣기 했는데 이 참에 제대로 정리해보려고 한다.

vscode 기준으로 크게 prettier, eslint, jsconfig 등의 설정이 있는데 차례로 소개하겠다.

prettier

프리티어는 말 그대로 예쁘게 코드를 보이게 해준다. 이게 무슨 말이냐면 들여쓰기 같은 것을 잘 하는 사람들은 문제가 없겠지만 코드가 길어지면 정리하기가 복잡해진다. 그리고 협업을 하다보면 서로 코딩 스타일이 달라서 머지할 때 문제가 생긴다. 그래서 반 강제적인 툴이 prettier이다. 

setting.json < .editorconfig < .prettieric

순으로 우선순위가 정해지는데 먼저 setting.json에 들어가거나 옵션에서 format on save를 선택한다.

 

setting.json :

"editor.formatOnSave": true,

"editor.defaultFormatter": "esbenp.prettier-vscode",

 

.editorconfig는 ide(vscode같은 에디터)가 다를 경우 세팅한다고 한다. 그런데 나는 아직 vscdoe를 사용하는 사람만 봤기 때문에 추후에 사용하게 된다면 내용을 추가하겠다.

 

setting.json에 prettier 옵션들을 넣어도 좋다. 그런데 협업을 할때는 .prettieric에 적용을 해야 코드가 꼬이지 않기 때문에 보통 설정한다.  설정은 공식문서에 하나하나 설명해놨기 때문에 그대로 보고 필요한 것을 적용하면 된다. (아래에 url을 적어두었다.)

리액트를 다루는 기술에서 나온 코드를 소개하겠다.

{
    "singleQuote": true,
    "semi": true,
    "useTabs": false,
    "tabWidth": 2,
    "trailingComma": "all",
    "printWidth": 80
  }

singleQuote : "" 말고 ''적용

semi : 코드뒤에 ;적용

useTabs : 공백대신 tab을 사용하여 들여쓰기 적용

이게 무슨말이냐면  말 코드에 스페이스바가 아니라 탭을 사용한 효과가 나타난다는 것이다. 시각장애인을 위해서 false를 지정해야 한다는 것 같다. https://www.reddit.com/r/javascript/comments/c8drjo/nobody_talks_about_the_real_reason_to_use_tabs/

trailingComma : 객체나 배열 뒤에 쉼표를 붙여준다. all을 설정하면 객체 마지막 key value다음에 쉼표가 붙는 것을 볼 수 있다.

printWidth : 지정한 글자수를 넘기면 줄을 넘긴다. 디폴트가 80이지만 경우에 따라서 조절하면 좋을 것 같다.

 

참고로 vscode 확장에서 prettier를 설치할 수도 있지만 npm으로 설치할 수도 있다. npm의 장점은 버전이 바뀌지 않는 점이다. 현업에서는 사용할지도 모르겠다. 일단은 알아만 두자. 특이점으로는 --save-exact가 있는데 이것도 버전때문이라고 한다.

npm install prettier --save-dev --save-exact

eslint

ESLint는 ECMAScript/JavaScript 코드에서 발견된 패턴을 식별하고 보고하는 도구로, 코드의 일관성을 높이고 버그를 방지하는 것을 목표로 합니다. 여러 면에서 몇 가지 예외를 제외하고는 JSLint 및 JSHint와 유사합니다. -- 공식홈페이지 번역

setting.json에 설정할 수도 있고 package.json의 

npm install eslint --save-dev # or yarn add eslint --dev 

$ npx eslint --init # or $ yarn run eslint --init

$ npx eslint yourfile.js # or $ yarn run eslint yourfile.js

 

설정은 아래와 같다. -- 공식홈페이지 설명

  • Environments - 스크립트가 실행되도록 설계된 환경. 각 환경에는 미리 정의된 특정 전역 변수 집합이 있습니다.
  • Globals - 스크립트가 실행 중에 액세스하는 추가 전역 변수.
  • Rules - 활성화된 규칙과 오류 수준.

env : 사전 정의된 전역 변수를 정의

parserOptions : ESLint를 사용하면 지원하려는 JavaScript 언어 옵션을 지정할 수 있다. 기본적으로 ESLint는 ECMAScript 5 구문만 지원한다. 파서 옵션을 사용하여 ECMAScript 6 및 JSX  대한 지원을 활성화하도록 해당 설정을 재정의할 수 있다.

    ecmaVersion : ECMAScript 버전 지정

    sourceType : script가 default. module이 존재하면 module

parser : 파서를 지정할 수 있다.  ex) "parser": "esprima",

globals : 전역변수 지정 가능 ex)"globals": { "var1": true, "var2": false }

plugins : 타사 플러그인 지정 가능. npm 설치 필요. ex) "plugins": [ "plugin1", "eslint-plugin-plugin2" ]

rules : 규칙. 아래 링크 참조

특정 규칙에 대한 경고를 활성화 비활성화 가능

/*eslint-disable no-alert, no-console */

alert('foo');
console.log('bar');

/*eslint-enable no-alert */

특정 라인의 모든 규칙 비활성화  alert('foo'); // eslint-disable-line

특정 라인의 특정 규칙 비활성화 alert('foo'); // eslint-disable-line no-alert

다음 라인 규칙 비활성화  // eslint-disable-next-line

settings : 공유 설정 추가

extends : 특정 구성 파일을 확장하려는 경우 파일 경로를 지정할 수 있다.

보통 아래 코드와 같이 recommended와 prettier를 같이 사용한다. 

구성파일을 사용하는 방법에는 두가지가 있는데 첫번째는 -c옵션을 사용하여 해당 위치를 CLI에 전달하는 것이다.

ex) eslint -c myconfig.json myfiletotest.js

두번째는 아까 말한 .eslintric.*(형식 여러가지), 또는 package.json을 이용하는 것이ㅏㄷ.

 

리액트를 다루는 기술 서버 설정(koa, esm 사용)

{
  "env": {
    "browser": true,
    "commonjs": true,
    "es2021": true,
    "node": true
  },
  "extends": ["eslint:recommended", "prettier"],
  "parserOptions": {
    "ecmaVersion": 12,
    "sourceType": "module"
  },
  "rules": {
    "no-unused-vars": "warn",
    "no-console": "off"
  }
}

 

아니 근데 겹쳐서 오류가 나네

npm install eslint-config-prettier -D

이러면 prettier에서 관리하는 코드 스타일은 eslint에서 관리하지 않는다.

 

공식문서에 더~~ 자세히 나와있다. 궁금하다면 공식문서를 읽어보자

 

config 설정

https://eslint.org/docs/2.0.0/user-guide/configuring

 

Documentation

Configuring ESLint ESLint is designed to be completely configurable, meaning you can turn off every rule and run only with basic syntax validation, or mix and match the bundled rules and your custom rules to make ESLint perfect for your project. There are

eslint.org

 

rule 설정

https://eslint.org/docs/rules/

 

List of available rules

no-unreachabledisallow unreachable code after `return`, `throw`, `continue`, and `break` statements

eslint.org

 

 

jsconfig

jsconfig는 vscode에서 제공하는 옵션이다. typescript를 사용하는 사람은 알고있는 tsconfig의 자손이라고 생각하면 된다.

compilerOptions

  target : 사용할 기본 라이브러리 지정 ex) es5, es6, es2015, es2016~~

  module : 모듈 코드 생성할 때 모듈 시스템 지정 ex) commonJS, es2015, es6

  baseUrl : 절대 경로를 가져오기 위한 기본 디렉토리

  paths : baseUrl 옵션을 기준으로 계산할 경로 매핑을 지정

  ~~ 나머지는 아래 공식문서에서 확인

exclude :  언어 서비스에게 해당 파일들이 너의 부분(your part)이 아니라고 한다. 즉 import 제외

ex) node_modules 제외

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6"
  },
  "exclude": ["node_modules"]
}

include : 프로젝트 파일을 명시적으로 표현. default는 모든 파일. include 속성이 명시되면 오직 그 파일들만 포함 

ex) src 디렉토리에 절대경로

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6"
  },
  "include": ["src/**/*"]
}

 

추천 jsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "baseUrl": "src",
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6"
  },
  "exclude": ["node_modules"]
}

 

참고자료

 

https://prettier.io/docs/en/options.html

 

Prettier · Opinionated Code Formatter

Opinionated Code Formatter

prettier.io

 

https://github.com/prettier/prettier-vscode

 

prettier/prettier-vscode

Visual Studio Code extension for Prettier. Contribute to prettier/prettier-vscode development by creating an account on GitHub.

github.com

 

https://eslint.org/docs/user-guide/getting-started

 

Getting Started with ESLint

Getting Started with ESLint ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code, with the goal of making code more consistent and avoiding bugs. In many ways, it is similar to JSLint and JSHint with a few exceptio

eslint.org

 

https://code.visualstudio.com/docs/languages/jsconfig

 

jsconfig.json Reference

View the reference for jsconfig.json.

code.visualstudio.com

 

 

728x90
LIST

'개발환경 > vscode' 카테고리의 다른 글

vscode 세팅  (0) 2021.06.19
vscode  (0) 2021.01.08
댓글
공지사항