Programming language/Typescript

Typescript 맛보기 3 - VS Studio Code에서 Prettier 적용하기

iKay 2019. 11. 2. 13:12
반응형

0. 서론

요즘 웹 개발자들 사이에서 언어로써는 Typescript가, IDE로써는 VS Studio Code가 많이 사용되는 것 같다. 사실 나 조차도 요즘 많이 사용하고 있는 언어와 환경이다.

 

이번에는 VS Studio Code IDE 상에서 Typescript 코드 format이 통일성을 유지할 수 있도록 강제하는 prettier(https://prettier.io/)에 대해 정리해 보도록 한다. 코드 format을 강제함으로 통일성을 유지하게 되면, 어느 누구와 협업하더라도 서로 코드를 내가 짠 코드처럼 쉽게 읽을 수 있어 생산성을 높일 수 있다.

 

가령, A라는 사람은 

if ( 1 + 2 === 3 ) 
{
    console.log('correct!')
}

이렇게 코딩할 수 있고, B라는 사람은

if (1 + 2 === 3) {
    console.log('correct!');
}

이렇게 코딩할 수 있다. 둘 모두 다른 로직은 아니지만 조건문을 표현하는 방식이 서로 다르기 때문에 읽는 사람마다 가독성이 떨어진다고 생각할 수 있다.

 

이와같은 경우처럼 code format을 강제함으로써 가독성을 높이기 위해 prettier를 사용한다.

 

prettier와 함께 eslint(https://eslint.org/)도 많이 사용되는데, 다음 번에 적용하는 법을 소개하겠다. 

 

 

1. typescript 환경 구축

typescript 환경이라고 가정했기 때문에, 매우 간단한 typescript 환경을  구축한다.  

 

typescrip에 대해 더 살펴보고 싶다면, 타입스크립트 맛보기(https://kay0426.tistory.com/39?category=822492)를 보자.

$ npm i -D typescript ts-node // devDependencies로 설치

 

2. typescript 코딩

아래와 같이 typescript를 코딩하고, 콘솔에 실행시켜보자. hello, world가 정상적으로 출력된다면 OK! 

interface Person {
    name: string;
    age: number;
    speak: () => void;
}


const person: Person = {
    name: "Amy", // 외따옴표와 쌍따옴표가 통일되지 않는다
    age: 24,
    speak() {
    console.log('hello, world'); // 코드 블록이 들쑥날쑥하다
    }
};

person.speak(); // 마지막 라인이 개행문자가 아니다
$ npx ts-node index

  hello, world // 출력 값

 

3. prettier 설치&설정

 

a. Prettier - Code formatter 설치

VS code stuido의 plug in에서 Prettier - Code formatter를 설치한다.

b. prettier package 설치

npm i -D prettier // devDependencies로 설치

 

c. .prettierrc.js 설정하기

프로젝트 디렉토리에 .prettierrc.js를 만들고, 아래의 내용을 입력한다. 

module.exports = {
    semi: true,
    trailingComma: 'all',
    singleQuote: true,
    printWidth: 80,
    tabWidth: 4,
};

 

설정에 대한 좀더 자세한 설명을 참고하려면 공식문서(https://prettier.io/docs/en/configuration.html)를 보면 된다.

 

d. .vscode/settings.json

프로젝트 디렉토리에 .vscode 디렉토리를 만들고 그 안에 아래 내용을 입력한다.

 

{
    "editor.formatOnSave": true,
    "typescript.tsdk": "node_modules/typescript/lib"
}

 

a, b, c, d를 설정한 후 VS Studio Code를 재시작하자.


4. 적용 여부 확인

'2. typescript 코딩'에서 주석으로 표시했던 내용들이 save할 때 마다 자동으로 변경된다. 

interface Person {
    name: string;
    age: number;
    speak: () => void;
}

const person: Person = {
    name: 'Amy',
    age: 24,
    speak() {
        console.log('hello, world');
    },
};

person.speak();

 

5. 결론

더 이상 코드블록, 외따옴표, 쌍다옴표, 세미콜론 표시, 공백, EOL 등으로 많은 고민을 하거나 시간을 쓸 필요 없이 로직을 만드는데 더 집중할 수 있게 됐다. 

 

반응형