전체 프로젝트 구조

만들거나 수정해야하는 폴더, 파일

Typescript 환경 만들어보기

  1. package.json 만들기

    $ mkdir besopt
    
    $ cd besopt
    
    $ mkdir seminar1 && cd seminar1
    
    $ npm init
    package.json 생성
     
    $ npm install --global yarn
    yarn 설치되어 있으면 패스 / --global 옵션은 전역 설치(시스템 레벨에서 설치)
    
    $ yarn add typescript ts-node --dev
    --dev 옵션은 devDependencies에 추가한다는 뜻
    
    $ yarn add @types/node --dev
    
  2. tsconfig.json

타입스크립트 컴파일러의 설정 파일입니다. 아래 명령어를 입력하면 tsconfig.json 파일이 생김.

$ tsc --init
message TS6071: Successfully created a tsconfig.json file.

기본 tsconfig.json 파일은 많은 옵션이 비활성화되어 있습니다.

다음과 같은 필요한 옵션만 간략하게 설정하여 사용합니다.

{
  "compilerOptions": {
    "target": "es6",
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "forceConsistentCasingInFileNames": true,
    "skipLibCheck": true,
    "moduleResolution": "node",
    "module": "commonjs",
    "pretty": true,
    "sourceMap": true,
    "outDir": "./dist",
    "allowJs": true,
    "noEmit": false,
    "esModuleInterop": true,
    "typeRoots": ["./src/types/express.d.ts", "./node_modules/@types"]
  },
  "include": ["./src/**/*"],
  "exclude": ["node_modules", "tests"]
}

["src/**/*"] 의 의미

  1. package.json 수정

Typescript 프로젝트를 개발할 때에는 ts-node를 사용합니다.

개발이 완료되면 Typescript 소스코드를 ES5 자바스크립트 코드로 변환해 node로 실행해야 합니다.

이를 위해 다음처럼 package.json 파일을 열고 scripts 항목에 dev와 build 명령을 추가합니다.

{
  "name": "servertest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "ts-node src",
    "build": "tsc && node dist",
    "test": "nodemon"
  },
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "express-validator": "^6.10.0",
    "gravatar": "^1.8.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.12.3",
    "request": "^2.88.2"
  },
  "devDependencies": {
    "@types/bcryptjs": "^2.4.2",
    "@types/express": "^4.17.11",
    "@types/mongoose": "^5.10.4",
    "@types/node": "^14.14.37",
    "nodemon": "^2.0.7",
    "ts-node": "^9.1.1",
    "typescript": "^4.2.3"
  },
  "author": "",
  "license": "ISC",
  "description": ""
}

저장하고

$ yarn install

scripts는 'yarn run 명령' 형태로 사용합니다.

$ yarn run dev
...
yarn run v1.22.10
$ ts-node src
{ name: 'Jane', age: 22 } { name: 'Jack', age: 33 }
$ yarn run build
yarn run v1.22.10
$ tsc && node dist
{ name: 'Jane', age: 22 } { name: 'Jack', age: 33 }

결론

대부분의 Typescript 프로젝트는 이런 과정을 거쳐 만들어지므로 프로젝트를 만들고 설정하는 작업에 익숙해져야 합니다.

  1. typescript는 개발 도움용 언어이다.
  2. 즉, 실행을 시킬 땐 타입스크립트 컴파일러 내에서 자바스크립트로 변환을 하여 실행시켜준다.
  3. 배포를 할 땐 yarn run build를 통해 dist 디렉토리를 만든 후, dist만 배포한다.

프로젝트 구조 알아보기의 사본

MongoDB 연결

1. 가입

mongoDB Atlas 가입 방법(무료 mongo DB 클라우드 서비스)

2. 연결

3. 모델 만들고 db에 저장해보기 (예시)