[Typescript] Typescript로 블록체인 구현 (3/3)

Lee_Sangmin·2022년 7월 27일
0

personal

목록 보기
4/9

TypeScript 프로젝트 설정

NextJS, NestJS, Create-React-App(CRA)를 사용하는 사람들은 수동으로 프로젝트를 설정할 일이 거의 없다.

그 외의 상황에서 프로젝트 설정하는 내용을 다룬다.
수동 프로젝트 설정의 세부 내용을 이해하는 것은 중요하다.
(가끔은 수동으로 작성해야 할 일이 생기기도 하고...)

npm init -y

으로 기본적인 package.json을 생성.

npm install -D typescript

으로 typescript에 대한 devDependencies를 생성한다.

touch tsconfig.json

tsconfig.json파일은 프로젝트 최상단에 생성 되어야 한다.


// tsconfig.json
{
  	// javascripit로 컴파일 하고자 하는 모든 디렉터리
  "include": ["src"],
  "compilerOptions": {
    // 자바스크립트 파일이 생성될 디렉터리
    "outDir": "build",
    "target": "ES6",
    "lib": ["ES6","DOM"]
    // DOM을 추가하는 경우, tsc가 document객체의 존재를 알게되어 사용 가능하다.
    // ex) document.queryselector(.~)
    "strict": true,
    "allowJs": true
    // ts내에서 자바스크립트 문법을 모두 허용
  }
}

// https://www.typescriptlang.org/tsconfig에서 tsconfig의 모든 option들을 확인할 수 있다.

  • 기존 javascript의 package나 library를 사용하기 위한 방법

1) ~.d.ts 작성

// myPackage.js
export function init(config) {
  return true;
}
export function exit(code) {
  return code + 1;
}
// myPackage.d.ts
interface Config {
  url: string;
}

declare module 'myPackage' {
  function init(config: Config): boolean;
  function exit(code: number): number;
}
// index.ts(작동 파일)
import { init, exit } from "myPackage"

2) // @ts-check 사용
tsconfig.js에 "allowJs": true 추가 필요.

// myPackage.js

// @ts-check

/*
 * Initializes the project
 * @param {object} config
 * @param {boolean} config.debug
 * @param {object} config.url
 * @return void
 */
export function init(config) {
  return true;
}
/*
 * Extis the project
 * @param {number} code
 * @return number
 */
export function exit(code) {
  return code + 1;
}

  • build과정 스킵

npm install -D ts-node

를 작성한 후, package.json내 "script"에 "dev"명령어를 추가한다.

// package.json
"scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "dev": "nodemon --exec ts-node src/idnex.ts",
    "lint": "next lint"
  },

  • typescript로 정의되지 않은 package import하기

github : DefiniteTyped/DefinitelyTyped 내에 모든 NodeJS 모듈들이 정의되어 있다.
여러명의 개발자가 ts 사용자들을 위해 타입정의들을 작성해놓은 것.

해당 정의 내용들을 사용하는 방법은 terminal을 통해 이루어진다.
가령 express이라는 package를 사용하고 싶다면,

npm install express

우선 express를 다운로드 하고

npm install -D @types/express

을 통해 타입정의를 다운할 수 있다.

ts에게 node 내 모든 타입 정의를 알려주고 싶으면

npm install -D @types/node

명령어를 입력하면 되긴 한다.

ETC

  • 기타 정보

hashId 생성

import crypto from 'crypto'
// npm install -D @types/crypto를 통해 타입 정의를 알게 됨.

return crypto.creatHash('sha256').update(toHash).digest('hex');

(Block)Chain 구성 방법

class Block implements BlockShapte {
  public hash: string;
  constructor(
    public prevHash: string,
    public depth: number,
    public data: string,
  ){
    this.hash = Block.calculateHash(prevHash, depth, data);
  }

  static calculateHash(prevHash: string, depth: number, data: string){
    const toHash = `${prevHash}${depth}${data}`
	return crypto.creatHash('sha256').update(toHash).digest('hex');
  }
}
profile
FE developer

0개의 댓글