개발 이야기/Node

NodeJS + Typescript + Mongoose

석구석구 2020. 2. 25. 15:26

JS를 사용하다 보면, 서버도 Nodejs로 만들고 싶다는 욕망이 생깁니다. ㅎㅎ

 

서버와 프론트가 모두 TS로 이루어지면 타입을 공유할 수 있는 장점이 생깁니다.

 

 

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

1. 늘 그렇듯이 모듈들을 설치해 줍시다. 

웹팩과 타입스크립트, 웹팩에서 사용할 타입스크립트 로더, 노드 핫로더, 타입스크립트 변환 모듈입니다.

// webpack.config.js

const path = require('path');

module.exports = {
  entry: './app.ts',
  module: {
    rules: [
      {
        test: /\.(js|ts|tsx)$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  devtool: 'source-map',
  target: 'node',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  resolve: {
    extensions: ['.jsx', '.ts', '.tsx', '.js'],
    alias: {
      '@Types': path.resolve(__dirname, '../@types/'),
    },
  },
};

2. 웹팩 설정 파일 예시입니다.

  // package.json
 
  "scripts": {
    "start": "nodemon --watch src --delay 1 --exec 'ts-node' ./app.ts",
    "build": "webpack --config webpack.config.js"
  },

3. 패키지 설정 파일입니다.

// tsconfig.json

{
  "compilerOptions": {
    "target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
    "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,

    "strict": true /* Enable all strict type-checking options. */,
    "noImplicitAny": false /* Raise error on expressions and declarations with an implied 'any' type. */,

    "baseUrl": "./" /* Base directory to resolve non-absolute module names. */,
    "paths": {
      "@Types/*": ["../@types/*"]
    },
    "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,

    "inlineSourceMap": true /* Emit a single file with source maps instead of having a separate file. */,
    "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
  }
}

 

4. typescript 설정 파일입니다.

 

이제 app.ts 파일에 타입스크립트로 코드를 작성한 후 npm start로 서버를 구동시키면 됩니다.

 

여기에 몽구스를 얹어 봅시다.

npm i -d mongoose @types/mongoose
// UserTypes.ts

export default interface UserTypes {
    userId: string;
    pw: string;
    email?: string;
}
// model/User.ts

import { Document, Schema, model } from 'mongoose';
import UserTypes from '@Types/UserTypes'

export interface UserTypesModel extends UserTypes, Document {
}

const UserSchema = new Schema({
    userId: {
        type: String,
        required: true,
        unique: true
    },
    pw: String,

});

export default model<UserTypesModel>('User', UserSchema);

 

mongoose.Document를 확장해 주어야 하기 때문에 껄적지근하긴 하지만 UserTypes.ts를 클라이언트와 서버 양측에서 공유 가능하게 되었습니다. 백엔드와 프론트가 모델을 공유하기 때문에 인터페이스의 신뢰도도 올라가고, IDE 지원도 편리해집니다.

'개발 이야기 > Node' 카테고리의 다른 글

이벤트 구독 패턴 EventEmitter - 4  (0) 2022.01.10
버퍼 Buffer - 3  (0) 2022.01.10
모듈 Module - 2  (0) 2022.01.10
노드 NodeJS - 1  (0) 2022.01.09