TypeScript 개발환경 구축
TypeScrpit 파일(.ts)은 브라우저에서 동작하지 않으므로 TypeScript 컴파일러를 이용해 자바스크립트 파일로 변환해야 한다. 이를 컴파일이라한다.
TypeScript 설치
$ npm install -g typescript // 전역설치
$ tsc -v // 설치 확인
TypeScript 컴파일러
TypeScript 컴파일러(tsc)는 TypeScript 파일(.ts)을 자바스크립트 파일로 트랜스파일링한다.
// person.ts
class Person {
private name: string;
constructor( name: string ){
this.name = name;
}
sayHello() {
return "Hello, " + this.name;
}
}
const person = new Person('Lee');
console.log(person.sayHello());
트랜스파일링을 실행한다. tsc 명령어 뒤에 트랜스파일링 대상 파일명을 지정한다. 확장자 .ts는 생략가능하다.
$ tsc person
트랜스파일 실행시, 같은 디렉터리에 자바스크립트 파일(person.js)이 생성된다.
// person.js
var Person = /** @class */ (function() {
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
return "Hello, " + this.name;
};
return Person;
}());
var person = new Person('Lee');
console.log(person.sayHello());
이때 트랜스파일링된 person.js의 자바스크립트 버전은 ES3이다.
만약 자바스크립트 버전을 변경하려면 컴파일 옵션에 -t, --target을 사용한다.
// ES6 버전
$ tsc person -t es6
트랜스파일링이 성공하여 자바스크립트 파일이 생성되었으면, Node.js REPL을 이용해서 트랜스파일링된 person.js를 실행할 수 있게된다.
$ node person
Hello, Lee
여러 개의 TypeScript 파일을 한번에 트랜스파일링할 수도 있다.