카테고리 없음

Typescript, Hello world!

개발자_이훈규 2020. 5. 15. 15:41

 

 

Typescript, Hello world!

 

Environment

install typescript compiler(실은 Transpiling, 변환)

$ npm install -g typescript
$ tsc -v
Version 3.9.2

$ node -v
v10.15.3

 

 

Ch 1. Transpiling

tsc 을 이용해서 ts파일을 js파일로 변환시킨다.

person.ts file 작성

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로 트랜스파일링 (default : ES3)

$ tsc person

 

결과 확인
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());

 

tsc로 트랜스파일링 (ES6)

$ tsc person -t ES2015

 

결과 확인
class Person {
    constructor(name) {
        this.name = name;
    }
    sayHello() {
        return "Hello, " + this.name;
    }
}
const person = new Person("Lee");
console.log(person.sayHello());

 

결과 실행

$ node person
Hello, Lee

 

 

Ch 2. config file

tsc옵션 설정 파일을 생성하여 트랜스파일링을 자동화한다.

$ tsc --init
message TS6071: Successfully created a tsconfig.json file.

 

tsconfig.json을 이용하려면 명령어를 tsc만 입력해야한다.

$ tsc

 

tsc 명령어만 사용하면 여러 파일을 동시에 트랜스파일링 할 수 있다.

 

ch 3. 여러 파일 tsc

파일 작성

// person.ts
export class Person {
    protected name: string;

    constructor(name: string) {
        this.name = name;
    }

    sayHello() {
        return "Hello, " + this.name;
    }
}
// stuent.ts
import { Person } from './person';

class Student extends Person {
    study(): string {
        return `${this.name} is studying.`;
    }
}

const student = new Student('Lee');

console.log(student.sayHello());
console.log(student.study());

 

트랜스파일링

$ tsc

 

결과실행

$ node student
Hello, Lee
Lee is studying.

 

 

ch 4. 변경 감지하여 자동 트랜스파일링, Hot-transpiling(?)

$ tsc --watch
[15:20:35] Starting compilation in watch mode...

[15:20:35] Found 0 errors. Watching for file changes.

[15:20:44] File change detected. Starting incremental compilation...

[15:20:44] Found 0 errors. Watching for file changes.

 

혹은

// tsconfig.json파일 안에 watch 추가

    ....
    "forceConsistentCasingInFileNames": true,
    "watch": true
  }
}
$ tsc

 

 

코드

https://github.com/leehunkyu00/typescript-tutorial