빵부스러기

[TypeScript 오류] 양방향 import 오류 - Dependency cycle detected. eslint(import/no-cycle)

borobong230 2024. 2. 6. 19:19

파일 구조

📦redux
 ┣ 📂slice
 ┃ ┗ 📜authSlice.ts
 ┣ 📜provider.tsx
 ┗ 📜store.ts


문제가 된 부분

 

// authSlice.ts
import { RootState } from '../store';
```
//store.ts
import authReducer from './slice/authSlice';



오류 문구

Dependency cycle detected. eslint(import/no-cycle)



오류 원인

서로가 서로를 import하고 있어서 순환 의존성 문제가 생겼습니다 (의존성이 순환적으로 참조)
모듈 로더가 해당 모듈의 로딩 순서를 결정할 수 없게 되어 예측 불가능한 결과 / 런타임 오류 유발하게 됩니다
(성능에 악영향을 끼침)

그래서 해당 규칙을 설정 시 eslint 규칙에서 경고를 줍니다. (사실 내가 설정함...)

 


해결방법

// authSlice.ts
import type { RootState } from '../store';


import type을 사용하면 실제 런타임 코드가 아닌 타입 정보만을 임포트 하기 때문에 순환 의존성에 영향을 주지 않습니다.

이렇게 사용하면 위에 eslint 오류를 간단하게 해결할 수 있습니다.


참조: https://github.com/reduxjs/redux-toolkit/issues/2390