728x90
반응형

전체 코드 (index.ts)

import * as CryptoJS from "crypto-js"

class Block {
    public index: number;
    public hash: string;
    public previousHash: string;
    public data: string;
    public timestamp: number;

    static calculateBlockHash = (
        index: number,
        previousHash: string,
        timestamp: number,
        data: string
    ): string => CryptoJS.SHA256(index + previousHash + timestamp + data).toString();

    static validateStructure = (aBlock: Block): boolean =>
        typeof aBlock.index === "number" &&
        typeof aBlock.hash === "string" &&
        typeof aBlock.previousHash === "string" &&
        typeof aBlock.timestamp === "number" &&
        typeof aBlock.data === "string";

    constructor(
        index: number,
        hash: string,
        previousHash: string,
        data: string,
        timestamp: number
    ) {
        this.index = index;
        this.hash = hash;
        this.previousHash = previousHash;
        this.data = data;
        this.timestamp = timestamp;
    }
}

const TeepoBlock: Block = new Block(0, "2020202020202", "", "Hello", 123456);

let blockchain: Block[] = [TeepoBlock];

const getBlockchain = (): Block[] => blockchain;

const getLatestBlock = (): Block => blockchain[blockchain.length - 1];

const getNewTimeStamp = (): number => Math.round(new Date().getTime() / 1000);

const createNewblock = (data: string): Block => {
    const previousBlock: Block = getLatestBlock();
    const newIndex: number = previousBlock.index + 1;
    const newTimestamp: number = getNewTimeStamp();
    const newHash: string = Block.calculateBlockHash(
        newIndex,
        previousBlock.hash,
        newTimestamp,
        data
        );
    const newBlock: Block = new Block(
        newIndex,
        newHash,
        previousBlock.hash,
        data,
        newTimestamp
        );
    addBlock(newBlock);
    return newBlock
}

const getHashforBlock = (aBlock: Block): string =>
    Block.calculateBlockHash(
        aBlock.index,
        aBlock.previousHash,
        aBlock.timestamp,
        aBlock.data
    )

const isBlockValid = (
    candidateBlock: Block,
    previousBlock: Block
): boolean => {
    if (!Block.validateStructure(candidateBlock)) {
        return false;
    } else if (previousBlock.index + 1 !== candidateBlock.index) {
        return false;
    } else if (previousBlock.hash !== candidateBlock.previousHash) {
        return false;
    } else if (getHashforBlock(candidateBlock) !== candidateBlock.hash) {
        return false;
    } else {
        return true
    }

}

const addBlock = (candidateBlock: Block): void => {
    if (isBlockValid(candidateBlock, getLatestBlock())) {
        blockchain.push(candidateBlock)
    }
}

createNewblock("second Block");
createNewblock("third Block");
createNewblock("fourth Block");

console.log(blockchain)

export { };

 

 

 

addBlock을 createNewblock 부분에 추가해준다.

const createNewblock = (data: string): Block => {
    const previousBlock: Block = getLatestBlock();
    const newIndex: number = previousBlock.index + 1;
    const newTimestamp: number = getNewTimeStamp();
    const newHash: string = Block.calculateBlockHash(
        newIndex,
        previousBlock.hash,
        newTimestamp,
        data
        );
    const newBlock: Block = new Block(
        newIndex,
        newHash,
        previousBlock.hash,
        data,
        newTimestamp
        );
    addBlock(newBlock);
    return newBlock
}

 

 

함수를 실행해준다.

createNewblock("second Block");
createNewblock("third Block");
createNewblock("fourth Block");

 

 

tsc-watch 로그를 보면..!

 

해시 링크드 리스트가 완성되었다!

728x90
반응형
728x90
반응형

블록체인의 기반은 블록들이 자신의 전 블록으로의 링크가 있다는 것이다.

 

블록들에 값이 제대로 들어있는지 확인해보자.

 

index.ts

import * as CryptoJS from "crypto-js"

class Block {
    public index: number;
    public hash: string;
    public previousHash: string;
    public data: string;
    public timestamp: number;

    static calculateBlockHash = (
        index: number,
        previousHash: string,
        timestamp: number,
        data: string
    ): string => CryptoJS.SHA256(index + previousHash + timestamp + data).toString;

    static validateStructure = (aBlock: Block): boolean =>
        typeof aBlock.index === "number" &&
        typeof aBlock.hash === "string" &&
        typeof aBlock.previousHash === "string" &&
        typeof aBlock.timestamp === "number" &&
        typeof aBlock.data === "string"

    constructor(
        index: number,
        hash: string,
        previousHash: string,
        data: string,
        timestamp: number
    ) {
        this.index = index;
        this.hash = hash;
        this.previousHash = previousHash;
        this.data = data;
        this.timestamp = timestamp;
    }
}

const TeepoBlock: Block = new Block(0, "20202020202", "", "Hello", 123456);

let blockchain: Block[] = [TeepoBlock];

const getBlockchain = (): Block[] => blockchain;

const getLatestBlock = (): Block => blockchain[blockchain.length - 1];

const getNewTimeStamp = (): number => Math.round(new Date().getTime() / 1000);

const createNewblock = (data: string): Block => {
    const previousBlock: Block = getLatestBlock();
    const newIndex: number = previousBlock.index + 1;
    const newTimestamp: number = getNewTimeStamp();
    const newHash: string = Block.calculateBlockHash(
        newIndex,
        previousBlock.hash,
        newTimestamp,
        data);
    const newBlock: Block = new Block(
        newIndex,
        newHash,
        previousBlock.hash,
        data,
        newTimestamp);
    return newBlock
}

const getHashforBlock = (aBlock: Block): string =>
    Block.calculateBlockHash(
        aBlock.index,
        aBlock.previousHash,
        aBlock.timestamp,
        aBlock.data
    )

const isBlockValid = (
    candidateBlock: Block,
    previousBlock: Block
): boolean => {
    if (!Block.validateStructure(candidateBlock)) {
        return false;
    } else if (previousBlock.index + 1 !== candidateBlock.index) {
        return false;
    } else if (previousBlock.hash !== candidateBlock.previousHash) {
        return false;
    } else if (getHashforBlock(candidateBlock) !== candidateBlock.hash) {
        return false;
    } else {
        return true
    }

}

const addBlock = (candidateBlock: Block): void => {
    if (isBlockValid(candidateBlock, getLatestBlock())) {
        blockchain.push(candidateBlock)
    }
}

export { };

 

분석해보자.

 

1. static으로 타입이 제대로 선언되었는지 확인하는 validateStructure 함수를 만들었다

    static validateStructure = (aBlock: Block): boolean =>
        typeof aBlock.index === "number" &&
        typeof aBlock.hash === "string" &&
        typeof aBlock.previousHash === "string" &&
        typeof aBlock.timestamp === "number" &&
        typeof aBlock.data === "string"

 

 

2. static으로 선언했었던 calculateBlockHash의 결과값을 반환하는 함수를 만든다.( 나중에 createNewblock에서 만든 newHash를 검증단계에서 검증하기 위해 )

const getHashforBlock = (aBlock: Block): string =>
    Block.calculateBlockHash(
        aBlock.index,
        aBlock.previousHash,
        aBlock.timestamp,
        aBlock.data
    )

 

 

3. 새로만들 블록과 제일 나중에 만들어진 블록을 인자로 가지고, 새로 만들어질 블록을 검증하는 함수를 만든다.

const isBlockValid = (
    candidateBlock: Block,
    previousBlock: Block
): boolean => {
    if (!Block.validateStructure(candidateBlock)) {
        return false;
    } else if (previousBlock.index + 1 !== candidateBlock.index) {
        return false;
    } else if (previousBlock.hash !== candidateBlock.previousHash) {
        return false;
    } else if (getHashforBlock(candidateBlock) !== candidateBlock.hash) {
        return false;
    } else {
        return true
    }

}
  • 먼저 타입을 검사한다 (validateStructure)
  • 최근의 index + 1과 새로만들 index가 다르면 false를 반환한다.
  • 새로 만들어질 블록의 이전 hash와 그 전에 만들어진 블록의 hash가 다르면 false를 반환한다
  • 만들어두었던 함수로 hash를 검증한다. ( calculateBlockHash 함수검증 )

 

 

4. 검증이 완료되면 blockchain에 push해주는 함수를 만든다.

const addBlock = (candidateBlock: Block): void => {
    if (isBlockValid(candidateBlock, getLatestBlock())) {
        blockchain.push(candidateBlock)
    }
}

 

 

이젠 전에 만들어두었던 createNewblock( 블록을 만드는 함수 )에 검증하는 부분을 추가하면 된다.

728x90
반응형
728x90
반응형

새로운 블록을 만드는 함수를 만들어보자. 만들어두었던 블록체인에 새 블록을 추가하는 과정은 다음글에서 검증하고 추가하도록 하겠다.

 

index.ts

import * as CryptoJS from "crypto-js"

class Block {
    public index: number;
    public hash: string;
    public previousHash: string;
    public data: string;
    public timestamp: number;

    static calculateBlockHash = (
        index: number,
        previousHash: string,
        timestamp: number,
        data: string
    ): string => CryptoJS.SHA256(index + previousHash + timestamp + data).toString()

    constructor(
        index: number,
        hash: string,
        previousHash: string,
        data: string,
        timestamp: number
    ) {
        this.index = index;
        this.hash = hash;
        this.previousHash = previousHash;
        this.data = data;
        this.timestamp = timestamp;
    }
}

const TeepoBlock: Block = new Block(0, "20202020202", "", "Hello", 123456);

let blockchain: Block[] = [TeepoBlock];

const getBlockchain = (): Block[] => blockchain;

const getLatestBlock = (): Block => blockchain[blockchain.length - 1];

const getNewTimeStamp = (): number => Math.round(new Date().getTime() / 1000);

const createNewblock = (data: string): Block => {
    const previousBlock: Block = getLatestBlock();
    const newIndex: number = previousBlock.index + 1;
    const newTimestamp: number = getNewTimeStamp();
    const newHash: string = Block.calculateBlockHash(
        newIndex,
        previousBlock.hash,
        newTimestamp,
        data);
    const newBlock: Block = new Block(
        newIndex,
        newHash,
        previousBlock.hash,
        data,
        newTimestamp);
    return newBlock
}


console.log(createNewblock("hello"), createNewblock("bye bye"))

export { };

 

 

createNewblock 함수를 자세히 들여다 보자.

const createNewblock = (data: string): Block => {
    const previousBlock: Block = getLatestBlock();
    const newIndex: number = previousBlock.index + 1;
    const newTimestamp: number = getNewTimeStamp();
    const newHash: string = Block.calculateBlockHash(
        newIndex,
        previousBlock.hash,
        newTimestamp,
        data);
    const newBlock: Block = new Block(
        newIndex,
        newHash,
        previousBlock.hash,
        data,
        newTimestamp);
    return newBlock
}

 

 

1. previouseBlock으로 가장 최근의 블록을 가져온다.

 

2. previousBlock에서의 index에 1을 더한 값으로 newIndex를 선언한다.

 

3. 전 글에서 설명했던 getNewTimeStamp 함수로 newTimeStamp를 선언한다.

 

4. static으로 선언했던 calculateBlockHash로 새로운 Hash를 만든다.

 

5. 선언했던 자료들과 인자값인 data를 가지고 새로운 블록을 만들어준다.

728x90
반응형
728x90
반응형

이제 새로운 블록을 만들어보자.

 

새로운 블록을 만들기 위해서는 해쉬를 계산해야한다.

 

먼저 crypto-js를 설치하자.

$ npm i crypto-js

 

그다음 블록체인이 추가될 때 사용할 함수를 static으로 선언하고 return값을 지정해준다.

static으로 선언한 메소드를 사용하면 별도의 인스턴스 없이 바로 클래스의 메소드를 쓸 수 있다.

 

index.ts

import * as CryptoJS from "crypto-js"

class Block {
    public index: number;
    public hash: string;
    public previousHash: string;
    public data: string;
    public timestamp: number;

    static calculateBlockHash = (
        index: number,
        previousHash: string,
        timestamp: number,
        data: string
    ):string => CryptoJS.SHA256(index + previousHash + timestamp + data).toString()

    constructor(
        index: number,
        hash: string,
        previousHash: string,
        data: string,
        timestamp: number
        ) {
        this.index = index;
        this.hash = hash;
        this.previousHash = previousHash;
        this.data = data;
        this.timestamp = timestamp;
    }
}

const TeepoBlock: Block = new Block(0, "20202020202", "", "Hello", 123456);

let blockchain: Block[] = [TeepoBlock];

console.log(blockchain)

export {};

 

 

이제 나중에 사용할 함수들을 추가하자.

import * as CryptoJS from "crypto-js"

class Block {
    public index: number;
    public hash: string;
    public previousHash: string;
    public data: string;
    public timestamp: number;

    static calculateBlockHash = (
        index: number,
        previousHash: string,
        timestamp: number,
        data: string
    ):string => CryptoJS.SHA256(index + previousHash + timestamp + data).toString()

    constructor(
        index: number,
        hash: string,
        previousHash: string,
        data: string,
        timestamp: number
        ) {
        this.index = index;
        this.hash = hash;
        this.previousHash = previousHash;
        this.data = data;
        this.timestamp = timestamp;
    }
}

const TeepoBlock: Block = new Block(0, "20202020202", "", "Hello", 123456);

let blockchain: Block[] = [TeepoBlock];

const getBlockchain = (): Block[] => blockchain;

const getLatestBlock = (): Block => blockchain[blockchain.length -1];

const getNewTimeStamp = (): number => Math.round(new Date().getTime() / 1000);


console.log(blockchain)

export {};

 

getBlockchain 함수는 말 그대로 Block을 반환한다.

getLatestBlock 함수는 가장최근의 블록을 반환한다.

getNewTimeStamp 함수는 timestamp 속성을 새로 지정해주기 위한 함수이다.

 

 

728x90
반응형
728x90
반응형

먼저 블록 구조를 만들어보자. Block 클래스를 만들어준다.

 

index.ts

class Block {
    public index: number;
    public hash: string;
    public previousHash: string;
    public data: string;
    public timestamp: number;
    constructor(
        index: number,
        hash: string,
        previousHash: string,
        data: string,
        timestamp: number
        ) {
        this.index = index;
        this.hash = hash;
        this.previousHash = previousHash;
        this.data = data;
        this.timestamp = timestamp;
    }
}

export {};

 

 

인스턴스를 만들어준다.

 

index.ts

class Block {
    public index: number;
    public hash: string;
    public previousHash: string;
    public data: string;
    public timestamp: number;
    constructor(
        index: number,
        hash: string,
        previousHash: string,
        data: string,
        timestamp: number
        ) {
        this.index = index;
        this.hash = hash;
        this.previousHash = previousHash;
        this.data = data;
        this.timestamp = timestamp;
    }
}

const TeepoBlock: Block = new Block(0, "20202020202", "", "Hello", 123456);

export {};

 

 

 

블록체인을 만들어준다. 블록체인이랑 블록들이 배열로 연결된 형태이다.

index.ts

class Block {
    public index: number;
    public hash: string;
    public previousHash: string;
    public data: string;
    public timestamp: number;
    constructor(
        index: number,
        hash: string,
        previousHash: string,
        data: string,
        timestamp: number
        ) {
        this.index = index;
        this.hash = hash;
        this.previousHash = previousHash;
        this.data = data;
        this.timestamp = timestamp;
    }
}

const TeepoBlock: Block = new Block(0, "20202020202", "", "Hello", 123456);

let blockchain: Block[] = [TeepoBlock];

console.log(blockchain)

export {};

 

tsc-watch 를 보면

 

완벽하게 블록이 들어간 것을 확인할 수 있다.

728x90
반응형
728x90
반응형

JS에서 문제가 생기는것을 막기 위해 ts파일에서 만든  interface들은 js로 컴파일되지 않는다.

 

다만 js파일에 interface를 넣고 싶을 때 우리는 Class를 이용할 수 있다. index.ts파일을 다음과 같이 바꿔보자.

 

index.ts

class Human {
    public name: string;
    public age: number;
    public gender: string;
    constructor(name:string, age:number,gender?:string) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
}

const person = new Human("Teepo",28,"male")

const sayHi = (person: Human):string => {
    return `Hello ${person.name}, you are ${person.age}, you are a ${person.gender}`
}

console.log(sayHi(person))

export {};

 

하나씩 분석해보자.

 

 

1. 먼저 Human이란 Class를 선언했고, 각각의 속성에 타입을 지정해주었다. public은 객체지향 언어의 특징중 하나인 접근 지정자로써, 자세한 내용은 검색을 통해 알 수 있다. constructor는 생성자로 클래스가 호출 될 때마다 실행이 되는 메소드이다.

class Human {
    public name: string;
    public age: number;
    public gender: string;
    constructor(name:string, age:number,gender?:string) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
}

 

 

2. person이라는 Human 클래스의 인스턴스를 만들어준다 여기서 인자값으로 지정해준 것들이 생성자가 실행되어 인스턴스가 각각의 속성으로 가지게 된다.

const person = new Human("Teepo",28,"male")

 

 

3. 함수를 선언할 때 인자값의 타입을 Human 클래스로 지정한다. 그다음 클래스가 가지는 속성으로 파라미터들을 지정해준다.

const sayHi = (person: Human):string => {
    return `Hello ${person.name}, you are ${person.age}, you are a ${person.gender}`
}

 

728x90
반응형

'Typescript > 이론' 카테고리의 다른 글

TypeScript | 이론 | Interfaces  (0) 2021.10.05
TypeScript | 이론 | Types  (0) 2021.10.05
Typescript | 이론 | 세팅하기  (0) 2021.10.05
728x90
반응형

만약 Object 타입을 지정해주려면 어떻게 해야 할까

 

먼저 TypeScript가 Object를 이해할 수 있게 해야 한다. 그리고 올바른 타입인지 검사해야 한다.

 

그러기 위해선 우리는 Interface를 써야한다. 먼저 아래와 같이 index.ts를 수정해보자.

 

 

index.ts

interface Human {
    name: string;
    gender: string;
    age: number;
}

const person = {
    name: "Teepo",
    gender: "male",
    age: 22
}

const sayHi = (person: Human):string => {
    return `Hello ${person.name}, you are ${person.age}, you are a ${person.gender}`
}

console.log(sayHi(person))

export {};

 

차근차근 하나씩 보자.

 

1. 먼저 interface 부분에서 해당 Object가 가지는 속성들의 타입을 지정해준다.

interface Human {
    name: string;
    gender: string;
    age: number;
}

 

 

 

2. 그 다음 실제 사용할 객체를 선언해준다.

const person = {
    name: "Teepo",
    gender: "male",
    age: 22
}

 

3. 함수를 선언할 때 인자로 들어오는 객체의 타입을 Human으로 지정해준다. ( 2번에 선언한 person과 상관없음 )

const sayHi = (person: Human):string => {
    return `Hello ${person.name}, you are ${person.age}, you are a ${person.gender}`
}

 

4. 실제 사용할 때 미리 선언해둔 객체를 넣어서 함수를 실행해준다. ( 이것이 2번에서 선언한 person )

console.log(sayHi(person))

 

 

이렇게 각각 속성들에 타입을 지정해주는 방법과 interface를 이용한 Object 타입 지정을 해보았다.

728x90
반응형

'Typescript > 이론' 카테고리의 다른 글

TypeScript | 이론 | Class  (0) 2021.10.05
TypeScript | 이론 | Types  (0) 2021.10.05
Typescript | 이론 | 세팅하기  (0) 2021.10.05
728x90
반응형

Typescript의 좋은 점은 Typed 언어라는 건데, 그 뜻은 어떤 종류의 변수와 데이터인지 설정해주는 것이다.

 

index.ts를 다음과 같이 수정해보자.

 

index.ts

const sayHi = (name, age, gender) => {
    console.log(`Hello ${name}, you are ${age}, you are a ${gender}`)
}

sayHi("Teepo",28,"male");

export {};

 

sayHi 함수 위에 마우스를 올려보면

 

 

이렇게 세가지의 인자 값의 타입이 모두 any로 되어있는 것을 볼 수 있다. 타입이 지정되지 않을 땐 이렇게 any로 자동 타입이 지정된다. 마지막에 있는 void는 함수가 어떤 값을 반환하는지 나타내주는 것이다. 만약 반환 값이 없으면 void로 설정된다.

 

이번엔 타입을 지정해보자.

 

index.ts

const sayHi = (name:string, age:number, gender:string) => {
    console.log(`Hello ${name}, you are ${age}, you are a ${gender}`)
}

sayHi("Teepo",28,"male");

export {};

 

name에 string, age에 number, gender에 string 이라는 타입을 지정해주었다.

 

age에 number가 아닌 string으로 선언을 해보면

 

 

이렇게 빨간 줄로 에러가 뜨는 것을 확인할 수 있다.

 

반환 값의 타입을 지정하려면

 

index.ts

const sayHi = (name:string, age:number, gender:string):string => {
    return `Hello ${name}, you are ${age}, you are a ${gender}`
}

sayHi("Teepo",28,"male");

export {};

 

이렇게 인자값을 선언한 뒤 타입을 지정해주고 반환 값을 설정해주면 된다.

 

sayHi의 반환값을 보기위해 함수를 console.log 안에 넣어보자.

 

index.ts

const sayHi = (name:string, age:number, gender:string):string => {
    return `Hello ${name}, you are ${age}, you are a ${gender}`
}

console.log(sayHi("Teepo",28,"male"));

export {};

 

 

이렇게 하고 실행을 해주면

 

정상적으로 로고가 찍히는 것을 볼 수 있다.

 

 

이번엔 tsc-watch라는 프로그램을 깔아보자.

$ npm i tsc-watch --dev

 

그다음 dist폴더를 생성해주고 pakage.json 파일을 수정해준다.

 

pakage.json

{
  "name": "Typescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start" : "tsc-watch --onSuccess \" node dist/index.js \""
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/jest": "^27.0.2",
    "awesome-typescript-loader": "^5.2.1",
    "ts-jest": "^27.0.5",
    "webpack": "^5.56.1",
    "webpack-dev-server": "^4.3.1"
  },
  "dependencies": {
    "tsc-watch": "^4.5.0"
  }
}

 

 

그다음 tsconfig.json파일을 수정해주고 src폴더를 생성한 뒤 index.ts파일을 넣어준다.

 

tsconfig.json

{
    "compilerOptions" : {
        "module" : "commonJS",
        "target": "ES3",
        "sourceMap": true,
        "outDir": "dist"
    },
    "include": [
        "src//**/*"
    ],
    "exclude": ["node_modules"]
}

 

 

이렇게 되면 내 모든 typescript는 src로 들어갈거고 컴파일 된 것들은 dist로 들어갈 것이다.

 

하고 npm start를 해보면!

 

이 오류가 뜰 수 있다. 당황하지말고 아래 명령어를 입력해주자.

$ npm i -D @types/node typescript ts-node

 

 

혹시나 아래와 같은 오류가 뜬다면 pakage.json안의 name과 프로젝트 최상위 폴더의 이름이 다른 것이니 주의하도록 하자.

 

 

이제 npm start를 해보면!

 

성공적으로 tsc-watch가 실행된 것을 볼 수 있다.

728x90
반응형

'Typescript > 이론' 카테고리의 다른 글

TypeScript | 이론 | Class  (0) 2021.10.05
TypeScript | 이론 | Interfaces  (0) 2021.10.05
Typescript | 이론 | 세팅하기  (0) 2021.10.05
728x90
반응형

타입스크립트에 관한 내용을 이해하기 쉽게 설명한 사이트가 있다.

https://joshua1988.github.io/ts/why-ts.html#% ED%83%80% EC% 9E%85% EC% 8A% A4% ED%81% AC% EB% A6% BD% ED% 8A% B8% EB% 9E%80

 

Why TypeScript? | 타입스크립트 핸드북

타입스크립트란? 타입스크립트는 자바스크립트에 타입을 부여한 언어입니다. 자바스크립트의 확장된 언어라고 볼 수 있습니다. 타입스크립트는 자바스크립트와 달리 브라우저에서 실행하려면

joshua1988.github.io

 

 

타입스크립트로 간단한 블록체인 만들기! 시작해보자. 

 

먼저 npm init으로 초기 npm 설정을 해준다.

$ npm init

 

typescript를 설치해준다. ( npm 모듈에 관한 글은 블로그 내에서 확인 부탁드립니다. )

$ sudo npm install –g typescript

 

추가적으로 설치해준다. 

$ npm install webpack webpack-dev-server awesome-typescript-loader ts-jest @types/jest --save-dev

 

프론트엔드 개발자의 영원한 친구가 돼버린 webpack과 그 친구 webpack-dev-server를 설치해줍니다. 그리고 공식 문서에는 ts-loader를 사용하던데요, 저희는 가볍게 무시하고 awesome-typescript-loader를 설치해줍니다. 딱 이만큼만 설치하면 됩니다. ES6를 한 번 사용해보려고 babel이며 babel-core며. babelrc파일이며 온갖 이상한 npm파일과 설정 파일을 생성한 기억이 한 번쯤은 있으실 텐데요, 타입스크립트는 여기까 지가 끝입니다. (행복합니다.) 그리고 테스트를 위한 jest를 설치해줍니다. @type/jest와 함께 설치해야 합니다.

 

참조

https://github.com/JaeYeopHan/typescript_playground

 

GitHub - JaeYeopHan/typescript_playground

Contribute to JaeYeopHan/typescript_playground development by creating an account on GitHub.

github.com

 

 

 그다음 진행하고자 할 프로젝트 폴더 내에 tsconfig.json 파일을 만들어 어떻게 JavaScript로 변환하는지

알려주면서 몇몇 옵션을 준다.

 

 

tsconfig.json

{
    "compilerOptions" : {
        "module" : "commonJS",
        "target": "ES3",
        "sourceMap": true,
    },
    "include": [
        
    ]
}

 

먼저 compilerOptions는 말 그대로 컴파일러 옵션에 관한 내용을 정의하는 것이다.

module은 node.js를 평범하게 사용하고 다양한걸 import 하거나 export 할 수 있게 만든다.

target은 어떤 버전의 JavaScript로 컴파일되고 싶은지 적는 것이다.

sourcemap은 sourcemap 처리를 하고 싶은지 알려준다.

 

아래 부분에 include 에는 컴파일 과정에서 포함할 파일의 배열을 적으면 된다.

또한 exclude에 node_modules를 설정해준다.

 

 

바로 추가해보자.

 

tsconfig.json

{
    "compilerOptions" : {
        "module" : "commonJS",
        "target": "ES3",
        "sourceMap": true,
    },
    "include": [
        "index.ts"
    ],
    "exclude": ["node_modules"]
}

 

기본적인 설정이 끝났다. 이제 index.ts 파일을 만들어 아래와 같이 작성한 후 컴파일해보자.

 

index.ts

console.log("hello");

 

tsc명령어를 입력한다. tsc는 ts파일에 있는 이 코드를 컴파일해서 index.js와 index.js.map을 만들어준다.

$ tsc

 

tsc 명령어 후 모습

 

 

이젠 package.json파일을 수정해서 npm startindex.ts파일을 컴파일하고 실행하도록 해보자.

 

package.json

{
  "name": "typescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js",
    "prestart": "tsc"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/jest": "^27.0.2",
    "awesome-typescript-loader": "^5.2.1",
    "ts-jest": "^27.0.5",
    "webpack": "^5.56.1",
    "webpack-dev-server": "^4.3.1"
  }
}

 

npm start 명령어를 실행해보자.

 

$ npm start

 

 

index.js, index.js.map 파일이 만들어지고

index.ts 파일에 작성해두었던 console.log("hello") 가 정상적으로 실행되었다.

 

 

728x90
반응형

'Typescript > 이론' 카테고리의 다른 글

TypeScript | 이론 | Class  (0) 2021.10.05
TypeScript | 이론 | Interfaces  (0) 2021.10.05
TypeScript | 이론 | Types  (0) 2021.10.05

+ Recent posts