본문 바로가기

클라이언트/TypeScript
[타입스크립트(TypeScript)] 웹스톰(Webstorm) 타입스크립트 컴파일

app을 실행하기 위해서는 타입스크립트 파일을 컴파일해서 자바스크립트 파일을 생성해야 한다.

타입스크립트 파일 수정할 때마다 다시 tsc 명령을 하는 건 너무나 귀찮은 일이다.

CLI에 tsc 명령 시 뒤에 --watch를 추가할 수도 있고, IDE에서 제공하는 기능을 사용할 수도 있다.

나는 웹스톰의 File Watchers를 설정해서 컴파일했다.


1. typescript를 설치한다.

tsc 명령어 경로를 지정해야 하기 떄문에 설치가 필요하다.

npm install typescript @types/node --save-dev

2. Settings > Tools > File Watchers에 들어가서 <custom> Template을 추가한다.


3. 컴파일 상세 설정을 해준다.

주로 설정해야 할 것은 Tool to Run on Changes 부분이다.

  • Program
    설치한 typescript의 tsc 경로( node_modues > .bin > tsc )를 설정한다.

  • Arguments
    TypeScript 파일을 컴파일할 때 사용할 옵션을 추가한다.
    tsconfig.json을 넣으면 tsconfig.json의 설정을 사용하여 컴파일한다.

    ◾ --target : javascript 코드의 ECMAScript 버전을 지정한다.
        ~ ES5, ES6 ...

    ◾ --module : 모듈 시스템을 지정한다.
        ~ commonjs, amd, es6 ..

    ◾ --sourceMap : 소스맵 파일을 생성한다.(디버깅, 개발 시 유용)

  • Output paths to refresh
    변환된 javascript 파일과 소스맵 파일을 저장할 경로를 설정한다.
    변경된 파일을 감지하고 IDE 내에서 새로고침한다.

-p tsconfig.json

dist/$FileNameWithoutAllExtensions$.js:$FileNameWithoutExtension$.js.map

$FileParentDir$

File Watcher 설정을 마치고 TypeScript 파일을 작성한 후 저장하면?


File Watcher에 의해 js 파일로 변환된다!

- app.ts

let userInput: unknown;
let userName: string;

userInput = 5;
userInput = 'Hana';
if (typeof userInput === 'string') {
  userName = userInput; 
}

function generateError(message: string, code: number): never {
  throw { message: message, errorCode: code };
}

generateError('An error occurred', 500);


- app.js

let userInput;
let userName;
userInput = 5;
userInput = 'Hana';
if (typeof userInput === 'string') {
    userName = userInput;
}
function generateError(message, code) {
    throw { message: message, errorCode: code };
}
generateError('An error occurred', 500);
//# sourceMappingURL=app.js.map

※ 컴파일 옵션은 https://www.typescriptlang.org/docs/handbook/compiler-options.html 참고

 

Documentation - tsc CLI Options

A very high-level overview of the CLI compiler options for tsc

www.typescriptlang.org