NestJs - Path alias

choko's avatar
Jun 29, 2024
NestJs - Path alias

ref https://webreaper.dev/posts/tsconfig-paths-setup/


 
  • Nest에서 멀리 있는 파일을 상대 경로로 import 시킬 경우, 코드가 복잡해진다.
    • import MyComponent from "../../../components/MyComponent";
  • Path alias 기능을 사용하면, 아래처럼 깔끔하게 줄일 수 있다.
    • import MyComponent from "@components/MyComponent";
    •  
  1. tsconfig.json setup
      • tsconfig.json의 compilerOptions.path 부분에 alias 시키고픈 경로를 다음과 같이 추가
      { "compilerOptions": { "baseUrl": ".", // root of your "paths" below. Required if "paths" is defined "paths": { /*1)*/ "@components": ["src/components"], // enables us to use @components/MyComponent /*2)*/ "@components/*": ["src/components/*"] // enables us to use @components/MyComponent } } }
       
  1. 사용
    1. "@components": ["src/components"]
        • src/components 폴더에 index.ts 파일 생성 후, 폴더 안 export를 모아주어야 함.
        export * from './components.controller' export * from './components.module' export * from './components.service'
        • 다음과 같이 사용할 수 있다.
        import { componentsModules } from '@components';
         
        💡
        대신, 위와 같이 사용할 경우 문제가 있다. components.controller를 DI 하고 싶은 경우, 에러가 발생한다. (index.ts를 한번 더 타고 넘어가서 D가 제대로 안되는듯..) 이 경우 아래 방법을 사용하자
         
         
    2. "@components/*": ["src/components/*"]
        • index.ts 파일 생성할 필요 없음, 아래와 같이 사용하면 됨
        import { componentsModules } from '@components/components.module';
       
Share article

Tom의 TIL 정리방