NestJS 에서 path alias 설정하기 (feat. TypeORM, Jest)

modolee
CrocusEnergy
Published in
5 min readNov 4, 2020

alias 설정 이유

  • 상대 경로로 지저분하게 설정되어 있는 경로를 깔끔하게 정리하기 위해서 alias를 사용합니다.

alias 설정 전

import { AuthResDto } from ‘../../src/auth/dto/response.dto’;
import { AuthService } from ‘../../src/auth/auth.service’;

alias 설정 후

import { AuthResDto } from ‘@auth/dto/response.dto’;
import { AuthService } from ‘@auth/accounts.service’;

프로젝트 구조

  • NestJS를 이용해서 만든 프로젝트의 기본 구조의 대략적으로 아래와 같습니다.
./
├── package.json
├── src
│ ├── auth
│ │ ├── auth.service.ts
│ │ └── auth.service.spec.ts
│ ├── app.controller.ts
│ ├── app.module.ts
└── ormconfig.ts
├── test
│ ├── app.e2e-spec.ts
│ └── jest-e2e.json
├── tsconfig.json
├── tsconfig.paths.json
└── tsconfig.paths.json

tsconfig.paths.json

  • 기본적인 소스코드에 적용되는 alias 설정
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@root/*": ["./src/*"],
"@auth/*": ["./src/auth/*"]
}
}
}

tsconfig.json

  • tsconfig.paths.json을 상속 받아서 사용
{
"extends": "./tsconfig.paths.json",

... (나머지 설정)

}
  • 이렇게 2가지만 설정해도 일반적으로 사용하는데에는 문제가 없습니다.

package.json

TypeORM을 위한 설정

  • TypeORM CLI를 이용해서 Migration 명령을 사용하고 있다면 추가 설정이 필요 할 수도 있습니다.
  • 저는 ormconfig.ts 파일에서 alias를 사용하기 때문에 아래와 같이 옵션을 추가했습니다.
  • yarn 또는 npm을 통해서 typeorm cli를 실행 시킬 때 추가 하는 기본적인 명령에 -r tsconfig-paths/register 옵션을 추가합니다.
// package.json
{
...

"scripts": {
"typeorm": "node -r tsconfig-paths/register -r ts-node/register ./node_modules/typeorm/cli.js --config src/ormconfig.ts",
"migration:create": "yarn typeorm migration:create",
"migration:run": "yarn typeorm migration:run",
"migration:revert": "yarn typeorm migration:revert",
}

...
}

Jest Unit 테스트를 위한 설정

  • yarn test를 이용해 unit 테스트 할 때 에러가 발생한다면, 아래 설정을 추가해야 합니다.
  • 설정을 추가하면 src/auth/auth.service.spec.ts 파일과 같은 unit 테스트 파일에서 alias를 사용할 수 있습니다.
  • package.json과 살짝 다르니 주의하세요.
  • 경로에 src가 빠진 이유는 rootDir이 기본적으로 src로 설정되어 있기 때문입니다.
// package.json
{
...

"jest": {
...

"rootDir": "src",
"moduleNameMapper": {
"^@root/(.*)$": "<rootDir>/$1",
"^@auth/(.*)$": "<rootDir>/auth/$1"
}

...
}

...
}

jest-e2e.json

  • Jest End-to-End 테스트를 위한 설정
  • yarn test:e2e 실행 시 기본적으로 이 파일의 설정을 따릅니다. 그래서 e2e 테스트에 alias를 사용하려면 해당 파일에 설정을 추가해야합니다.
  • Unit 테스트를 위한 설정과 약간 다릅니다.../src가 추가 된 이유는 e2e 테스트 파일에서의 rootDirtest 디렉터리를 의미합니다. 그래서 실행 코드가 있는 src 디렉터리를 가리키기 위해 ../src을 추가해 줘야 합니다.
{
...
"rootDir": ".",
"moduleNameMapper": {
"^@root/(.*)$": "<rootDir>/../src/$1",
"^@auth/(.*)$": "<rootDir>/../src/auth/$1"
}

...
}

참고

--

--