Node.js Project 설정 가이드 (1) - typescript 설치

Node.js Project 설정 가이드 (1) - typescript 설치
Photo by Mohammad Rahmani / Unsplash

이 포스트 시리즈는 다른 프로젝트 세팅에서 복사 & 붙여넣기가 아니라, 빈 프로젝트부터 typescript, babel, eslint, prettier, alias 설정까지 해나가는 과정을 그 의미와 함께 설명한다.

What is typescript?

TypeScript는 Microsoft에서 개발하고 유지하는 오픈소스 프로그래밍 언어로, JavaScript의 상위 집합(superset)이다.

JavaScript의 모든 기능을 포함하면서도 정적 타입, 인터페이스, 클래스, 모듈 등의 추가 기능을 제공하여 JavaScript를 보다 안정적이고 관리하기 쉽게 만들어준다.

TypeScript는 브라우저나 서버에서 직접 실행되지 않고, 먼저 JavaScript로 변환되어 사용되는 컴파일 언어이다.

환경 소개

현재 필자의 개발환경은 다음과 같다.

  • node : v18.15.0
  • npm : 9.5.0
  • vscode : 1.80.1
  • macOS ventura 13.2.1, apple silicon

이런 버전이 달라질 때 향후 설명할 부분에서 적게 또는 크게 바뀌는 부분이 생기게 된다. 포기하거나 주변사람에게 의존하기 보다는 구체적인 키워드로 직접 검색해서 해결하다보면 이 때 또 실력이 많이 증가하니 끝까지 해보자.

프로젝트 시작하기

우선 적당한 위치에 프로젝트 루트 폴더를 만들고 진입하자.

➜  javascript-projects mkdir my-nodejs-proj
➜  javascript-projects cd my-nodejs-proj 
➜  my-nodejs-proj

여기서 npm init 실행 후 웬만한건 다 엔터키로 넘어가자.

➜  javascript-projects mkdir my-nodejs-proj
➜  javascript-projects cd my-nodejs-proj 
➜  my-nodejs-proj npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (my-nodejs-proj) 
version: (1.0.0) 
description: 
entry point: (index.js) 
test command: 
git repository: 
keywords: 
author: 
license: (ISC) 
About to write to /Users/davelee/Documents/projects/javascript-projects/my-nodejs-proj/package.json:

{
  "name": "my-nodejs-proj",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this OK? (yes) 
➜  my-nodejs-proj 

이렇게 하면 폴더 내에 pacakage.json 이 생성된다. code . (code 띄우고 .) 을 실행해 이 폴더를 vscode로 열자. (혹시 command line에서 이게 안된다면 vscode 실행 -> cmd + shift +p -> Shell Command : install 'code' command in PATH )

typescript 설치

npm install --save-dev typescript 로 typescript 를 설치한다.

그리고 프로젝트 root 폴더에 tsconfig.json을 만들어보자.

{
    "compilerOptions": {
      "target": "ES2020",
      "module": "ES2020",
      "esModuleInterop": true,
      "strict": true,
    },

    "include": ["src"]
  }

여기서 target의 의미는 알고 있어야 한다. typescript는 결국 javascript로 컴파일 된 후 실행되게 된다. 이 때 컴파일 될 javascript의 버전을 의미한다. javascript는 es6이후로 수시로 많은 문법과 기능이 추가되고 있으며, 일부는 추가된지 몇 년만에 대부분의 실무자가 사용하기도 한다.

자신의 코드가 실행될 환경이 nodejs의 어떤 버전인지 알고 있다면, 혹은 테스트로 만드는 프로젝트라면 가급적 높게 잡으면 좋겠다.

helloWorld 파일 생성

src폴더를 하나 만들고 그 안에 index.ts 를 생성하자. 그리고 다음과 같은 내용으로 채워보자. (세미콜론 없고 쌍따옴표)

console.log("hello world")

ts-node 설치 & 간단한 실행

원래 typescript 프로젝트는 전체를 javascript로 컴파일해서 이를 다시 실행하는 형식이다. 그렇지만 ts-node를 쓰면 간단하게 그때그때 컴파일하면서 실행해볼 수 있다.

➜  my-nodejs-proj npx ts-node src/index.ts
hello world
➜  my-nodejs-proj 

hello world 가 출력되었다면 성공이다.