본문 바로가기

Programming/Nodejs tips

Nodejs + Express + Typescript 프로젝트 세팅

필요 선행 작업

$ npm i -g yarn
$ npm i -g typescript

 

*** 만약 git 이 설치되어 있지 않다면, 아래 명령어 실행

$ brew install git

프로젝트 생성

프로젝트를 시작할 폴더를 생성 후 해당 폴더 내에서 아래 명령어 실행

$ yarn init -y
$ tsc --init
$ git init

라이브러리 추가

Express, nodemon, typescript 설치

$ yarn add express
$ yarn add -D @types/express @types/node ts-node typescript nodemon

tsconfig.json 설정

tsc --init 명령으로 파일이 생성되었을 것이다. 해당 config 에 typescript 컴파일 옵션을 추가한다.

{
  "compilerOptions": {
    "allowUnreachableCode": false,
    "alwaysStrict": true,
    "module": "CommonJS",
    "esModuleInterop": true,
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": true,
    "outDir": "dist",
    "lib": ["esnext"]
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}

.gitignore 생성 및 설정

# dist
dist/

# node_modules
node_modules/

# yarn
yarn.lock
yarn-error.log

Main index.ts 및 "hello world" API 생성

$ mkdir src
$ touch src/index.ts

 

이제 index.ts 에 express 를 활용해 API 를 만들 수 있다.

import express from 'express';

const app = express();

app.get('/', (req, res, err) => {
  res.send('hello world');
});

const PORT = process.env.PORT || 5001;

app.listen(PORT, () => {
  console.log('server on ' + PORT);
});

package.json 설정


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

로컬 서버 띄우기

스크립트 명령어, run server 를 실행시켜 서버를 띄워준다.
nodemon 이 실행되며 어떤 포트에서 listening 하고 있는 서버인지 로그를 보여준다.

 

그리고 curl 명령으로 테스트!

$ yarn run server
$ curl http://localhost:5001

 

'Programming > Nodejs tips' 카테고리의 다른 글

Nodejs 비밀번호 암호화  (0) 2022.11.18
Nodejs 로 텍스트 파일 가져오기  (0) 2022.11.16