[실수 정리] 순환 참조 문제

김종현·2024년 7월 18일
0

My Mistakes

목록 보기
2/3
post-thumbnail

문제 상황

Features 폴더를 통해 기능별로 코드를 나누는 과정에서 모듈을 불러오는 과정에서 참조 오류 발생.

ReferenceError: Cannot access 'setAllNotificationsRead' before initialization



문제 파악 시도

  1. 선언 문제인가 싶어서 순서를 확인 및 수정 시도 => 실패(원인 아님)

  2. import 해 오는 순서를 변경 => 실패(원인 아님)

  3. 문제의 원인이 되는 notificationSelectors.ts의 notificationsError 코드 주석 처리 및 분석 => 실패(원인 아님)

문제 원인 및 분석

순환 참조 오류

밑줄 친 부분이 문제가 된 부분이다.

index.ts
    ├── import { setAllNotificationsRead, notificationsSlice } from "./notificationsSlice";
    ├── import { fetchNotifications, deleteNotification } from "./notificationsAsyncThunks";
    └── import { selectAllNotifications, notificationsStatus, notificationsError } from "./notificationsSelectors";

notificationsSlice.ts
    └── import { fetchNotifications, deleteNotification } from "./index";

위와 같이 notificationsSlice는 index에서 thunk 함수를 참조하는데 index에서도 notificationsSlice의 모듈을 참조하기 때문에 순환 참조가 발생한 것이다.

계속해서 서로 꼬리를 물고 있기 때문에 발생한 오류인 것.

문제 해결

index.ts
    ├── import { setAllNotificationsRead } from "./notificationsSlice";
    ├── import { fetchNotifications, createNotification, deleteNotification } from "./notificationsAsyncThunks";
    └── import { selectAllNotifications, notificationsStatus, notificationsError } from "./notificationsSelectors";

notificationsSlice.ts
    └── import { fetchNotifications, deleteNotification } from "./notificationsAsyncThunks";

notificationsSlice에서 import 해오는 thunk 함수들을 notificationsAsyncThunks에서 직접 가져와 순환 참조 문제를 해결.

느낀점

우선 기능별로 코드를 모듈화하고 정리할 때 index에서 모두 import하고 export 하는 방식인 '배럴 패턴(Barrel Pattern)은 확실한 장점이있다.

  1. 임포트 경로가 짧아지고 명확해진다.

  2. 각 기능별 모듈을 한 곳에서 관리하므로 구조 이해가 용이하며 import문이 지저분해지지 않는다.

  3. 새로운 모듈 추가 시, 배럴 파일만 수정하면 되기 때문에 유지 보수가 용이하다.

하지만 이 패턴을 사용하다보면 무지성으로 관련 기능을 import 해오고 export 하는 단순 반복 과정 속에서 모든 참조 경로를 index로 두게 되므로 이 부분을 유의해야겠다.

profile
고양이 릴스 매니아

0개의 댓글