Express.js로 웹서버 만들기
npm init
npm init -y # 정보입력을 자동으로 해준다.
npm install express
프로젝트 폴더에 node_modules 폴더가 생성된다. 자동으로 express package가 참조하고 있는 다른 npm packages도 설치된다.
npm install typescript ts-node nodemon @types/node @types/express
nodemon: 서버 코드를 변경할 때마다 서버를 자동으로 재시작 해준다.
ts-node: Node.js상에서 TypeScript Compiler를 통하지 않고도, 직접 TypeScript를 실행시킨다.
TypeScript로 짜여진 코드를 JavaScript로 컴파일하는 옵션을 설정하는 파일이다. TypeScript 컴파일은 tsc라는 명령어를 사용한다.
# tsconfig.json 파일 생성
npx tsc --init
root 폴더 아래 src/app.ts를 작성한다.
import express, { Request, Response, NextFunction } from 'express';
const app = express();
# app.get의 url로 접속하면 해당 블록의 코드를 실행한다.
app.get('/welcome', (req: Request, res: Response, next: NextFunction) => {
res.send('welcome!');
});
# app.listen의 포트로 접속하면 해당 블록의 코드를 실행한다.
app.listen('1234', () => {
console.log(`
################################################
🛡️ Server listening on port: 1234🛡️
################################################
`);
});
nodemon, ts-node를 이용하여 서버를 시작하는 스크립트 작성
...
"scripts": {
"start": "node dist/app.js",
"build": "tsc -p .",
"dev": "nodemon --watch \"src/**/*.ts\" --exec \"ts-node\" src/app.ts"
}
...
아래 명령어로 서버를 시작하고, http://localhost:1234/welcome 에 접속한다!
yarn dev
참고: https://velog.io/@qhgus/Node-Express-TypeScript-%ED%99%98%EA%B2%BD-%EC%84%B8%ED%8C%85