상세 컨텐츠

본문 제목

[TS / Node] TS + Node.js + Express + Babel(option) + eslint로 개발환경 세팅하기

Log.Develop/JS&TS

by bluayer 2020. 7. 23. 13:08

본문

서론

이 포스트를 쓰게 된 계기는,

내가 원하는 저 조합(TS + Node.js + Express + Babel + eslint)으로 개발환경을 세팅했으며

이에 대해 잘 정리된 글을 생각보다 찾기 힘들어서다.

위의 조합으로 개발환경을 세팅하는 가장 강력한 이유는 TS(TypeScript)를 사용하고 싶기 때문이라고 생각한다.

'정적 타입이 주는 안정감'이란 단어는 얼마나 HIP한 단어인가!! (안타깝게도 JS 개발자들에겐 HIP하게 느껴진다ㅠㅠ)

아무쪼록 저렇게 세팅을 해보도록 하자.

(다만, 이 글은 Node.js + Express 세팅에 이미 익숙한 사람을 전제로 쓰여진 글이다.)

 

미리 보는 결론

결론은 매우매우 간단하다는 것이다.

 

1) tsconfig 생성 및 수정

2) eslint 설정

3) babel 설정

4) 각종 모듈 설치

5) 자기 취향에 맞게 npm에 커맨드 세팅(build, start 등)

 

이렇게 5가지 설정만 하면 세팅을 잘 할 수 있다.

(참고로, tslint는 deprecated 되었기 때문에 eslint를 쓰는 것이 현명한 방법이라고 할 수 있다.)

 

tsconfig 생성 및 수정

TypeScript를 사용하기 위해서는 Node.js가 깔려있어야 한다는 전제가 있다.

적당한 LTS 버전을 아래의 링크에서 설치하도록 하자.

https://nodejs.org/ko/

 

Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

 

그 다음에 bash(혹은 terminal 혹은 zsh이겠지만 bash라고 다 명명하겠다)에 다음과 같은 커맨드를 입력한다.

 

$ npm install -g typescript

 

이제 ts를 설치했으니 기본적인 세팅을 해야한다.

 

$ tsc --init

 

위와 같은 커맨드를 사용해도 좋고,
package.json이 있는 root dir에 tsconfig.json을 만들어도 좋다. 

tsconfig.json에 대한 설명은 아래 링크에 아주아주 자세하게 잘 나와있다. 

https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

 

tsconfig.json · TypeScript

Overview # The presence of a tsconfig.json file in a directory indicates that the directory is the root of a TypeScript project. The tsconfig.json file specifies the root files and the compiler options required to compile the project. A project is compiled

www.typescriptlang.org

 

참고로 내가 쓰고 있는 tsconfig.json은 다음과 같은 형태인데,

build 했을 때 ./dist 폴더(outDir)로 모든 내용이 담긴다는 점과,

ES6(EcmaScript 6)버전을 타겟으로 사용한다는 점이 좀 특별하다고 할 수 있다.

 

더보기
{
  "compilerOptions": {
    /* Basic Options */
    "target": "es6",                        /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "lib": ["es5", "es6"],                  /* Specify library files to be included in the compilation. */
    "allowJs": false,                       /* Allow javascript files to be compiled. */
    "outDir": "./dist",                     /* Redirect output structure to the directory. */
    "rootDir": "./",                        /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */

    /* Strict Type-Checking Options */
    "strict": true,                         /* Enable all strict type-checking options. */

    /* Additional Checks */
    "noUnusedLocals": true,                 /* Report errors on unused locals. */
    "noUnusedParameters": true,             /* Report errors on unused parameters. */

    /* Module Resolution Options */
    "module": "commonjs",                   /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "types": ["node"],                      /* Type declaration files to be included in compilation. */
    "esModuleInterop": true,                /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */

    /* Experimental Options */
    "experimentalDecorators": true,         /* Enables experimental support for ES7 decorators. */

    /* Advanced Options */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  },
  "include": [
    "src/**/*.ts",
    "tests/**/*.ts"
  ],
  "exclude": [
    "./node_modules/**",
    "./dist/**"
  ]
}

 

ESLint 설정

솔직히 입맛대로 하면 된다.

핵심적인 것은 간단하다.

이미 있는 tsconfig와 새로 설치할 모듈을 통해 parser, plugin, extend를 잘 세팅해주기만 끝난다.

 

먼저 모듈을 설치한다.

 

$ npm -i eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser --save-dev

 

{ 
	"parser": "@typescript-eslint/parser",
 	"parserOptions": {
		"project": "tsconfig.json",
		"sourceType": "module"
	},
	"plugins": [
		"@typescript-eslint"
	],
	"extends": [
		"eslint:recommended",
		"plugin:@typescript-eslint/eslint-recommended"
	],
}

 

위와 같이 잘 세팅해주고,

그 다음에는 선택적으로 이 아래에 본인이 원하는 rules(원하는 문법 강제)와 env를 설정해주기만 하면 된다.

 

Babel 설정(선택)

Babel 설정을 선택이라고 하는 이유는,

ts에서 lint를 쓰고 싶어서 들어온 사람들을 위한 배려라고 할 수 있다.

Babel이 하는 일은 트랜스파일러로,

본 포스트에서는 우리가 작성한 ts 문법을 기존 JS 버전 중 하나로 바꿔주는 역할을 할 것이다.

이런 번거로운 일을 하는 것은 여러 가지 이유가 있겠지만,
'기존의 js의 배포 툴 등을 더 용이하게 쓰기 위해서'라고 필자는 생각한다.

 

아무쪼록 바벨 세팅은 사실 개발할 때는 필요가 없기 때문에 본인의 선택이며,
필자는 본 글에서 소개를 하긴 하겠다!

일단 모듈을 설치한다.

 

$ npm -i @babel/cli @babel/core @babel/plugin-proposal-class-properties @babel/plugin-proposal-object-rest-spread @babel/plugin-transform-runtime @babel/preset-typescript @babel/preset-env

 

그리고 root dir에 .babelrc 라는 이름의 파일을 만들고 다음과 같이 입력한다.

{
    "presets": [
        "@babel/preset-typescript",
        ["@babel/preset-env", { "targets": { "node": 6 } }]
    ],
    "plugins": [
        "@babel/proposal-class-properties",
        "@babel/proposal-object-rest-spread",
        "@babel/plugin-transform-runtime",
        "lodash"
    ]
}

 

그렇다면 빌드할 준비가 끝난 것이다!!

(이후에 빌드를 실행하다가 잘 안될 가능성도 있다! 이는 dependency 관계가 수정되었거나 하는 경우가 있어서, 다른 모듈을 설치해 줘야 하는 상황이기 때문인데 그럴 땐 검색을 해서 찾아보도록 하자!!)

 

각종 모듈 설치

본인의 입맛에 맞게 쓰고 싶은 모듈들을 설치하면 된다.

 

$ npm -i @types/express @types/node ts-node

 

이렇게 사실 3가지만 설치하더라도 큰 문제가 없다!

(물론 기존의 node + express 세팅이 되어 있어야 한다!  npm을 통해 express 모듈도 설치해주도록 하자)

 

여기까지 따라왔다면..

본인의 입맛에 맞게 커맨드를 설정해주면 된다.

내가 주로 package.json에 설정해놓은 npm 커맨드는 다음과 같다.

 

    "start": "npm run build && nodemon ./dist/app.js",
    "type-check": "tsc --noEmit",
    "type-check:watch": "npm run type-check --watch",
    "build": "npm run build:js",
    "build:js": "babel src --out-dir dist --extensions \".ts,.tsx\" --source-maps inline",
$ npm run build

npm run build를 실행하면 build 과정을 통해 js로 이루어진 dist 폴더가 생기게 된다.

이를 실행까지 하고 싶다면 start 커맨드만 사용해도 된다.

 

또한 type-check가 지속적으로 이루어지게 하고 싶다면 npm run type-check:watch 를 통해 확인할 수 있다.

 

후기

TS를 세팅하는 건 번거롭긴 하지만, 엄청나게 어렵진 않다.

물론 중간 중간 모듈을 사용하기 위해 설치해야 하는 경우도 있고, ts를 지원하지 않는 경우도 가끔 존재한다.

하지만 꽤나 major한 기능들은 대부분 ts를 지원하기 때문에 번거로움 정도만 있다.

 

정적 타입이 주는 안정감을 즐겨보자!!

관련글 더보기

댓글 영역