node에서의 타입스크립트 개발 환경 구성

slobber·2023년 8월 15일
0
post-thumbnail

node에서의 타입스크립트 개발 환경 구성에 대한 기록


기본 세팅

프로젝트 폴더를 생성후 npm init or yarn init을 통해 package.json 파일을 생성

npm init or yarn init

tsc init

  • tsconfig.json 파일
tsc --init

TypeScript 컴파일러에 --init 적용해서 typescript 프로젝트를 initialize 할 수 있습니다.


express 설치

  • typescript로 서버를 사용하기 위한 모듈을 설치해줍니다.
yarn add -D typescript nodemon ts-node @types/node
  • express도 마찬가지로 @types/express를 함께 설치
yarn add express
yarn add -D @types/express

설치 확인

  • package.json을 다음과 같이 작성
"scripts": {
    "start": "nodemon --exec ts-node src/index.ts"
},
  • src/app.ts 파일에 간단한 코드 작성
console.log('Hello TypeScript node')

절대 경로 설정

  • tsconfig-paths 설치
yarn add -D tsconfig-paths
  • tsconfig.json 설정
{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "moduleResolution": "node" /* Skip type checking all .d.ts files. */,
    "sourceMap": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "skipLibCheck": true,
    "baseUrl": ".",
    /** 절대 경로 설정 */
    "paths": {
      "@src/*": ["src/*"]
    }
  },
  "exclude": ["node_modules"],
  "include": ["src"]
}
  • package.json을 scripts 수정
  "scripts": {
    "dev": "nodemon --watch 'src/**/*.ts' --exec ts-node -r tsconfig-paths/register src/app.ts",
  },

환경 변수 설정

yarn add dotenv
  • 프로젝트 루트에 .env 파일 생성
ex)
DB_HOST=localhost
DB_USER=root
DB_PASS=1234
  • package.json을 scripts 수정
  "scripts": {
    "dev": "NODE_ENV=dev nodemon --watch 'src/**/*.ts' --exec ts-node -r tsconfig-paths/register src/app.ts",
  },
  • cross-env 모듈 설치
yarn add cross-env
  • package.json을 scripts 수정
  "scripts": {
    "dev": "cross-env NODE_ENV=dev nodemon --watch 'src/**/*.ts' --exec ts-node -r tsconfig-paths/register src/app.ts",
  },
profile
안녕하세요 성장하는 개발자입니다.

2개의 댓글

comment-user-thumbnail
2023년 8월 15일

개발자로서 성장하는 데 큰 도움이 된 글이었습니다. 감사합니다.

1개의 답글