NestJS에서 기본적으로 제공하는 타입스크립트 환경만 사용하다가 익스프레스에서 타입스크립트를 사용하려고 하니 조금 헤맸는데, 여러 자료들을 보고 익스프레스에 타입스크립트를 적용할 수 있었다. 익스프레스 프로젝트에서 타입스크립트를 사용하는 과정에 대해 정리한다.
필요한 의존성 패키지들을 설치한다. 가장 먼저 익스프레스를 설치한다.
npm i express
다음으로 타입스크립트 사용에 필요한 패키지들을 개발 의존성 패키지로 설치한다.
npm i -D typescript @types/node ts-node-dev
typescript
: 타입스크립트 패키지@types/node
: Node.js의 타입스크립트 정의 패키지ts-node-env
: nodemon처럼 개발 도중 파일이 변경되었을 때 노드 프로세스를 재실행하는 패키지이다. nodemon보다 속도가 빠르다고 한다.tsconfig.json
파일은 타입스크립트 컴파일 옵션을 담고 있는 파일이다. 이 파일이 위치한 곳이 타입스크립트를 사용하는 프로젝트의 루트 디렉터리가 되고, 다양한 컴파일 옵션들을 설정할 수 있는 파일이다.
tsconfig.json 파일을 명령어를 통해 간단하게 생성할 수 있다. 두 명령어 중 하나를 선택해서 생성할 수 있다.
npx tsc --init // 이것도 되고
tsc --init // 이것도 됨
명령어를 실행하면 다양한 옵션들이 기본적으로 포함된 상태로 tsconfig.json 파일이 생성된다. 기본 옵션들을 그대로 둔 상태에서 ts-node-dev
패키지를 사용해 서버를 실행하기 위해 package.json
파일의 scripts
필드를 수정한다.
"scripts": {
"start:dev": "NODE_ENV=dev tsnd src/app.ts --respawn --transpile-only --exit-child",
},
npm run start:dev
명령어로 서버를 실행할 수 있게 설정하였다.tsnd
는 ts-node-dev의 짧은 별칭이라고 한다.--respawn
: ts-node-dev가 사용하는 node-dev의 옵션으로, 스크립트가 종료된 후 변경 사항을 지켜보는 옵션.--transpile-only
: ts-node-dev가 사용하는 ts-node의 옵션으로, 타입스크립트의 transpileModule을 사용하는 옵션.--exit-child
: SIGTERM exit 핸들러를 자식 프로세스에 추가하는 옵션이라고 하는데, 아직은 무슨 옵션인지 잘 모르겠다.어쨌든 결과적으로 npm run start:dev를 실행하고 src 디렉터리의 app.ts 파일을 수정하면 서버가 자동으로 재실행된다.
src 디렉터리에 app.ts 파일을 추가하고 간단한 익스프레스 코드를 넣고 실행한다.
import express from "express";
const app = express();
const port = 3000;
app.get("/", (req, res) => {
console.log(process.cwd());
res.send("Hello World!");
});
app.listen(port, () => {
console.log(`Server app listening on port ${port}`);
});
npm run start:dev로 서버를 실행해 로그를 확인한다.
app.ts 파일이 수정되면 서버가 자동으로 재실행된다.
프로덕션 환경에서 실행하기 위해 tsconfig.json과 package.json의 scripts 필드를 수정한다.
tsc --init
명령어로 생성한 기본 tsconfig.json에서 rootDir
과 outDir
을 추가한다.
{
"compilerOptions": {
/* Language and Environment */
"target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
/* Modules */
"module": "commonjs" /* Specify what module code is generated. */,
"rootDir": "./src" /* Specify the root folder within your source files. */,
/* Emit */
"outDir": "./dist" /* Specify an output folder for all emitted files. */,
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
다음으로 package.json의 scripts를 수정한다. tsc로 빌드 후 dist 폴더의 app.js 파일을 실행할 수 있게 설정하였다.
"scripts": {
"start:dev": "NODE_ENV=dev tsnd ./src/app.ts --respawn --transpile-only --exit-child",
"build": "tsc",
"start:prod": "NODE_ENV=prod node dist/app.js"
},
개발자로서 성장하는 데 큰 도움이 된 글이었습니다. 감사합니다.