kakasoo

NestJS 모듈 배포를 위한 코드 작성 본문

프로그래밍/NestJS

NestJS 모듈 배포를 위한 코드 작성

카카수(kakasoo) 2023. 1. 11. 23:08
반응형
// package.json의 일부

{
  "dependencies": {
    "@nestjs/common": "^9.2.1",
    "@nestjs/testing": "^9.2.1",
    "typescript": "^4.9.4"
  },
  "devDependencies": {
    "@types/jest": "^29.2.5",
    "@types/node": "^18.11.18",
    "jest": "^29.3.1",
    "ts-jest": "^29.0.3"
  },
}

최소한의 라이브러리로 위와 같이 install을 진행했다.

NestJS 라이브러리를 만들 것이기 때문에 @nestjs/common과 @nestjs/testing을 install 하였고,

typescript를 쓰기 위해 typescript library와 각종 타입, 테스트를 위해 jest 등을 설치했다.

이 정도의 라이브러리만 가지고도 라이브러리를 배포하고, 또 다른 서비스에서 사용하기에 무리가 없다.

 

// package.json의 일부

{
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
}

package.json의 main property는 이 라이브러리의 시작점이기 때문에 dist/index.js를 가리키게 했고,

마찬가지로 types property는 ./dist/index.d.ts 파일을 가리키게 했다.

main은 깜빡할 일이 없겠지만, types는 자주 잊곤 한다.

types가 없다면 나중에 npm install 이후 해당 라이브러리의 타입 추론이나 자동 완성에 문제가 생긴다.

 

# 파일구조는 이게 전부

src
  ㄴ test
  ㄴ index.ts
  ㄴ regexp.constant.ts
  ㄴ regexp.module.ts
  ㄴ regexp.service.ts
.eslintrc.js
.gitignore
.prettierrc
LICENSE
nest-cli.json
package-lock.json
package.json
README.md
tsconfig.build.json
tsconfig.json

파일구조는 이게 전부다.

src 안에 test 폴더가 있어 의아할 수 있는데, package.json에 명시한 main으로부터 test로 연결된 파일은 없다.

그래서 빌드 이후, 해당 라이브러리를 배포할 때 dist 파일에 test 폴더는 생기지 않으니 안심해도 된다.

 

// index.ts
export * from './regexp.module';
export * from './regexp.service';
export * from './regexp.constant';

더군다나 index.ts는 위 세 줄이 전부다.

3개의 파일은 내가 필요한 것들만 작성했을 뿐 특별히 다른 요소나 패턴은 가지지 않는다.

NestJS 모듈 배포를 위해 봐야 할 거라면 regexp.module.ts 파일 하나 보는 걸로도 충분하다.

 

// regexp.module.ts

import { Module, DynamicModule } from '@nestjs/common';
import { RegExpService } from './regexp.service';

@Module({})
export class RegExpModule {
    static register(options: any): DynamicModule {
        return {
            module: RegExpModule,
            providers: [
                {
                    provide: RegExpService,
                    useValue: new RegExpService(),
                },
            ],
            exports: [RegExpService],
        };
    }
}

모듈은 위와 같이 작성되어 배포되어야 한다.

useFactory 등을 지원하는 모듈이 아니라면 register 메서드만 구현하면 되며, register는 파라미터를 받는다.

option으로 받은 값에 따라 다른 모듈이 생성되게끔 코드를 짜도 무방하며,

해당 메서드는 module, controllers, providers, exports 등을 갖춘 NestJS 모듈 형식을 반환한다.

 

my-library-name
  ㄴ src
    ㄴ index.ts # my library code's entry point

other-folder
  ㄴ node_modules
    ㄴ my-library
  ㄴ src

테스트 코드 외에 npm install 후 동작하는 걸 확인하고 싶을 때는 바로 배포할 필요까지는 없다.

다른 폴더에서 npm install ../my-library-name 와 같이 상대 경로를 치면 로컬 내에서 install이 가능하다.

물론 배포가 된 게 아니기 때문에 로컬에서만 가능한 일이지만, 이걸로도 다운로드 받은 것처럼 실행이 가능하다.

node.js 생태계는 npm을 이용해서 누구나 쉽고 간단하게 모듈을 배포하고 공유할 수 있게 되어 있다.

이 생태계를 이끄는 강한 원동력임과 동시에, node.js 개발자들이 자기 코드를 어디든 적용할 수 있게 해줘 뛰어난 생산성을 발휘한다.

반응형