[NICO] typescript BlockChain

jisookim·2024년 10월 14일

📍개발환경 세팅

(1) npm init -y 로 package.json 만들기 + package.json 안의 main으로 실행되는 index.js 지우기
(2) npm i -D typescript -D 를 넣음으로써 package.json 안의 devDependencies 안에 typescript가 추가됨!
(3) inside the src , make index.ts file.
(4) tsconfig.json <- 해당 파일을 만들어야 vsc가 우리가 typescript로 작업한다는 사실을 알게됨! => auto complete 해줌!

{
	"include": ["src"],
	"compilerOptions": {
		"outDir": "build",
        "target": "ES6"
	}
}
  • typescript가 "src" 폴더 안의 모든 typescript 파일들을 나중에 javascript로 바꿔주겠음! 하고 확인해 줌.
    -outdir : 자바스크립트가 생성될 폴더
    -target : 자바스크립트 버전 지정
    set the JS language version for emitted JS and include compatible library declarations.

(5) package.json 에 새로운 scripts 만들어주기

{
  "name": "typechain",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "build" : "tsc"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^5.6.3"
  }
}

lib : specify a set of bundled library declaration files that describe the target runtime environment. -> 내 자바스크립트 코드가 어디에서 동작할지 알려주는 것. 코드가 동작하는 환경에 따라, 타입스크립트는 기본적으로 API의 타입을 알기에, 타입에 대해서 auto complete를 제공함!

📍JS module을 TS에서 쓰는 법

declaration file : js code의 모양을 typescript에 설명해주는 파일

import {init, exit} from "myPackage";

📍JS file을 TS에서 쓰는 법

tsconfig.json 의 compilerOptions에 "allowJs": true 추가

import {init, exit} from "./myPackage";

TS가 js file의 함수의 타입을 추론해줌. (automatically)
js파일에서도 ts 기능을 이용하고 싶다면, 함수 위에 // @ts-check적어주면 됨.

// @ts-check
/** 
* @param {object} config
* @param {boolean} config.debug
* @param {string} config.url
* @returns {boolean}
*/
export function init(config){
return ture;
}

only based on comments, TS knows what functions they need to handle, which is inside the JS file.

📍개발환경 세팅 2 - ts-node & nodemon

npm i -D ts-node : ts-node가 컴파일할 필요 없이 타입스크립트 코드를 대신 실행해줌.
npm i nodemon : 설치하면 자동으로 커맨드를 재실행시켜줌

  "scripts": {
    "build": "tsc",
    "dev": "nodemon --exec ts-node src/index.ts",
    "start": "build/index.js"
  },

현재 scripts 상태!

npm i -D @types/node : 이걸 설치하면 nodejs의 모든 것에 대해서 타입스크립트에게 알려줄 수 있어!

0개의 댓글