Express.js와 TypeScript를 사용한 환경설정

채희태·2023년 8월 22일

개요

Express.js와 TypeScript를 결합하여 환경설정하는 방법을 알아보겠습니다.

1. 프로젝트 초기화

먼저, 프로젝트 폴더를 생성하고 Node.js 프로젝트를 초기화합니다.

mkdir my-express-app
cd my-express-app
npm init -y

2. Express.js와 TypeScript 설치

Express.js와 TypeScript 그리고 nodemon 라이브러리를 설치합니다.

npm install express 
npm install @types/node @types/express nodemon ts-node typescript --save-dev

3. TypeScript 설정 파일 생성

TypeScript 설정 파일 tsconfig.json을 프로젝트 루트 디렉토리에 생성합니다.

npx tsconfig --init
{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

    /* Language and Environment */
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    // "experimentalDecorators": true,                   /* Enable experimental support for legacy experimental decorators. */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
    // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
    // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */

    /* Modules */
    "module": "commonjs",                                /* Specify what module code is generated. */
    "rootDir": "./src",                                  /* Specify the root folder within your source files. */
    "moduleResolution": "node",                     /* Specify how TypeScript looks up a file from a given module specifier. */
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
    // "allowImportingTsExtensions": true,               /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
    // "resolvePackageJsonExports": true,                /* Use the package.json 'exports' field when resolving package imports. */
    // "resolvePackageJsonImports": true,                /* Use the package.json 'imports' field when resolving imports. */
    // "customConditions": [],                           /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
    // "resolveJsonModule": true,                        /* Enable importing .json files. */
    // "allowArbitraryExtensions": true,                 /* Enable importing files with any extension, provided a declaration file is present. */
    // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

    /* Emit */
    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
    "outDir": "./dist",                                   /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "verbatimModuleSyntax": true,                     /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
    // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  },
  "include": ["./src"]
}

target: 내보낸 자바스크립트 언어 버전을 설정하고 호환되는 라이브러리 선언을 포함합니다.
module: 생성할 모듈 코드를 지정합니다.
rootDir: 원본 파일 내에 루트 폴더를 지정합니다. (src폴더 내에서 개발이 진행될 것이므로 ./src로 지정)
moduleResolution: TypeScript가 지정된 모듈 지정자에서 파일을 검색하는 방법을 지정합니다. (일반적으로 node를 지정)
outDir: 내보낸 모든 파일에 대해 출력 폴더를 지정합니다. (=./dist폴더를 타입스크립트에서 컴파일된 자바스크립트 파일을 저장하는 출력 폴더로 지정)
그리고 외부에 설정한 "include": ["./src"]는 타입스크립트 파일이 있는 경로 입니다.

4. 소스 코드 디렉토리 구성

프로젝트 루트에 src 디렉토리를 생성하고, Express.js 애플리케이션 파일을 만듭니다.

mkdir src
touch src/app.ts

일반적으로 애플리케이션 파일명은 app.ts, index.ts, server.ts가 사용됩니다.

5. Express.js 애플리케이션 구성

src/app.ts 파일에 Express.js 애플리케이션을 구성합니다.

// env파일
PORT=5000
import express, {
  Request,
  Response,
  NextFunction,
  Application,
  ErrorRequestHandler,
} from "express";
import { Server } from "http";
import createHttpError from "http-errors";
import { config } from "dotenv";

config();

const app: Application = express();

app.get("/", (req: Request, res: Response, next: NextFunction) => {
  res.send("hello");
});

// 에러 핸들링 미들웨어
app.use((req: Request, res: Response, next: NextFunction) => {
  next(new createHttpError.NotFound());
});
const errorHandler: ErrorRequestHandler = (err, req, res, next) => {
  console.log(err.status);
  res.status(err.status || 500);
  res.send({ status: err.status, message: err.message });
};
app.use(errorHandler);

const PORT: number = Number(process.env.PORT) || 5000;
const server: Server = app.listen(PORT, () =>
  console.log(`server is on port ${PORT}`)
);

express 라이브러리에서 Application, Request, Response, NextFunction 등의 타입을 가져옵니다. 또한 Node.js의 내장 모듈인 http에서 Server 타입을 가져오고, http-errors와 dotenv 라이브러리를 가져옵니다.

config(): dotenv를 사용하여 환경변수를 로드합니다. 이렇게 하면 .env 파일에 정의된 환경변수를 사용할 수 있습니다.

app: express() 함수로 애플리케이션 객체를 생성합니다.

app.get("/"): 루트 경로(/)에 대한 GET 요청 핸들러를 등록합니다. 이 핸들러에서는 "hello" 문자열을 응답으로 보냅니다.

에러 핸들링 미들웨어:

app.use(): 미들웨어 함수를 등록합니다. 이 미들웨어는 모든 요청에 대해 호출되며, 등록된 핸들러 함수를 실행합니다.
미들웨어 함수에서 next(new createHttpError.NotFound())를 호출하여 존재하지 않는 경로에 대한 요청이 들어올 경우 404 Not Found 에러를 발생시킵니다.
errorHandler: 에러 핸들링을 위한 커스텀 에러 핸들러 함수입니다. 에러 객체의 상태 코드와 메시지를 클라이언트로 응답합니다.

app.use(errorHandler): 앞서 정의한 에러 핸들러를 등록합니다. 이 핸들러는 모든 에러에 대한 처리를 담당합니다.

PORT: 환경변수인 process.env.PORT 값을 읽어오거나, 기본값으로 5000을 사용합니다.

server: Express 애플리케이션을 특정 포트로 서버로 실행합니다. 서버가 실행되면 해당 포트에서 요청을 받을 준비가 됩니다.

6. package.json 스크립트 작성

{
  "name": "hantong-oms-server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon ./src/app.ts",
    "start": "node ./dist/app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/express": "^4.17.17",
    "@types/http-errors": "^2.0.1",
    "@types/node": "^20.5.1",
    "nodemon": "^3.0.1",
    "ts-node": "^10.9.1",
    "typescript": "^5.1.6"
  },
  "dependencies": {
    "dotenv": "^16.3.1",
    "express": "^4.18.2",
    "http-errors": "^2.0.0"
  }
}

"dev" 스크립트는 nodemon 패키지를 사용하여 개발 서버를 실행합니다. nodemon은 소스 코드가 변경될 때마다 자동으로 서버를 다시 시작하는 도구입니다. ./src/app.ts 파일을 감시하며 변경 사항이 있으면 서버를 자동으로 다시 시작합니다.
"start" 스크립트는 node 명령을 사용하여 실제 운영 서버를 실행합니다. ./dist/app.js 파일을 실행하여 Express.js 애플리케이션을 시작합니다. 주로 배포나 운영 환경에서 사용됩니다.

7. ts파일 컴파일링

npx tsc

위의 명령어를 입력하면 아래와 같은 컴파일링된 js파일이 생성됩니다.

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const http_errors_1 = __importDefault(require("http-errors"));
const dotenv_1 = require("dotenv");
(0, dotenv_1.config)();
const app = (0, express_1.default)();
app.get("/", (req, res, next) => {
    res.send("hello");
});
// 에러 핸들링 미들웨어
app.use((req, res, next) => {
    next(new http_errors_1.default.NotFound());
});
const errorHandler = (err, req, res, next) => {
    console.log(err.status);
    res.status(err.status || 500);
    res.send({ status: err.status, message: err.message });
};
app.use(errorHandler);
const PORT = Number(process.env.PORT) || 5000;
const server = app.listen(PORT, () => console.log(`server is on port ${PORT}`));

tsconfig 파일에서 outDir로 지정해 놓은 dist 폴더로 src폴더 안에 존재하는 ts파일에서 컴파일링된 js파일이 위의 코드와 같이 생성됩니다. (./dist/app.js)

8. 정리

├── dist/
│   ├── app.js
├── src/
│   ├── app.ts
├── node_modules/
├── .env
├── package.json
└── tsconfig.json

설정한 어플리케이션의 디렉토리는 위와 같습니다.
이렇게 디렉토리를 구성하고 코드 파일을 배치하면, Express.js와 TypeScript를 사용한 간단한 웹 서버를 실행할 수 있습니다.

profile
기록, 공부, 활용

0개의 댓글