⚙️ Node.js

[NodeJS] 아주 쉽게 타입스크립트 적용하기

Dogfoot_JW 2024. 9. 5. 16:58

Typescript 설치

현재 PC에 타입스크립트를 설치한다.

npm i -g typescript 

pakage.json 파일 생성

npm init -y

필요한 구성 요소 설치

npm i -D tsx @types/node express @types/express ts-node nodemon 

tsconfig.json 파일 생성

TypeScript로 짜여진 코드를 JavaScript로 컴파일하는 옵션을 설정하는 파일

npx tsc --init
  • 필요한 옵션 작성
{
  "compilerOptions": {
    "target": "ES2022", //ES2022 문법 적용
    "module": "commonjs", //어떤 모듈 방식으로 컴파일할지 설정
    "outDir": "./dist", //컴파일 후 js 파일들이 생성되는 곳
    "rootDir": "./src", //루트 폴더
    "strict": true, //strict 옵션 활성화
    "moduleResolution": "node", //모듈 해석 방법 설정: 'node' (Node.js)
    "resolveJsonModule": true, //JSON 모듈을 가져오기 허용
    "esModuleInterop": true,
    "sourceMap": true //소스맵 적용 여부
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}

pakage.json 수정


"main": "dist/index.js",
"scripts": {
    "start": "tsc -p . && node .", 
    "build": "tsc -p .",
    "dev": "nodemon --watch \"src/**/*.ts\" --exec \"ts-node\" src/index.ts"
  },

node . 에서 . 은 main을 뜻 한다. 따라서 node dist/index.js 가 되는 것이다.


소스파일 추가

mkdir src
touch src/index.ts

(선택사항) 소스맵 패키지 세팅

이 패키지는 컴파일 된 .js 파일에서 오류가 발생할 경우 .js.map을 통해 원본 소스코드 파일인 .ts 의 어디서 오류가 나는지 확인 시켜주는 패키지이다.

npm i source-map-support @types/source-map-support

<index.ts> 수정

import sourceMapSupport from 'source-map-support'

sourceMapSupport.install()