Express 초기 설정(타입스크립트)

김준엽·2022년 6월 7일
0

backend

목록 보기
1/2

Express란?

Express는 Node.js를 사용하여 서버 구축을 해주는 프레임워크입니다.


초기설정

여기시는 yarn을 이용해 패키지를 설치하겠습니다.

1. package.json 생성

프로젝트 디렉토리에서 package.json을 생성합니다.

yarn init -y

2. 필요한 패키지 설치

dependencies와 devDependencies를 구분해서 설치합니다.

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

dotenv : 환경설정을 도와주는 라이브러리(.env 파일을 읽어 스크립트에서 사용가능하게 해줍니다.)
nodemon : 코드 수정 시 서버를 자동으로 재시작해주는 라이브러리
ts-node : Node.js에서 타입스크립트를 실행시켜주는 라이브러리

3. tsconfig.json 생성

타입스크립트 컴파일 옵션 설정파일을 생성합니다.

npx tsc --init

tsconfig.json파일에 아래 설정을 추가합니다.

"rootDir": "./src"
"outDir": "./dist" 

npx tsc --init명령어를 사용하지 않고 tsconfig.json 파일을 직접 생성하는 방법도 괜찮습니다.

4. script 명령어 추가

package.json에 스크립트 명령어를 추가합니다.

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

dev 명령어에서 nodemon 옵션을 살펴 보겠습니다.
--watch : 변경 감지할 파일을 지정합니다.
--exec : 실행할 명령어를 지정합니다.
dev 명령어를 해석하면 'src 디렉토리 내 코드가 변경된 ts-nodesrc/app.ts를 실행한다' 입니다.

5. 기본파일 생성

src/app.ts 파일을 생성합니다.

import { config } from 'dotenv'
import express, { Application, NextFunction, Request, Response } from 'express'

config()

const app: Application = express()

app.get('/', (req: Request, res: Response, next: NextFunction) => {
  res.send('Express server with TypeScript')
})

const PORT = process.env.PORT || 3000

app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`)
})

6. ESlint, Prettier

.eslintrc.json 생성하고 필요한 패키지를 자동으로 설치합니다.

npx eslint --init

√ How would you like to use ESLint? · style       
√ What type of modules does your project use? · esm
√ Which framework does your project use? · none
√ Does your project use TypeScript? · Yes
√ Where does your code run? · browser
√ How would you like to define a style for your project? · guide
√ Which style guide do you want to follow? · standard    
√ What format do you want your config file to be in? · JSON

위 명령어를 이용하지 않고 직접 필요한 패키지를 설치하고 .eslintrc.json 파일을 만들어도 괜찮습니다.


prettier를 설정하기 위한 패키지를 설치합니다.

yarn add -D prettier eslint-config-prettier eslint-plugin-prettier

.prettierrc.json을 생성합니다.

{
  "jsxSingleQuote": true,
  "semi": false,
  "printWidth": 120,
  "proseWrap": "never",
  "singleQuote": true,
  "htmlWhitespaceSensitivity": "css",
  "endOfLine": "auto"
}

.eslintrc.json 파일에 아래와 같은 설정을 추가합니다.

'extends': ['plugin:prettier/recommended']
profile
프론트엔드 개발자

0개의 댓글