반응형
🔍 에러 상황
React Native 프로젝트에서 아래와 같은 코드를 작성했습니다:
import { colors } from '@repo/constants';
const styles = StyleSheet.create({
container: {
backgroundColor: colors.green[900],
},
});
그런데 앱을 실행했더니 다음과 같은 에러가 발생했습니다:
❌ Cannot read property 'green' of undefined
🤔 왜 이런 에러가 발생할까?
에러의 원인은 default export를 named import로 불러왔기 때문입니다.
📁 colors.ts
const colors = {
green: {
900: '#064E3B'
},
...
};
export default colors;
📁 index.ts
export * from './colors';
colors.ts는 default export지만,
index.ts에서는 named export로 넘기지 않았기 때문에
import { colors } from '@repo/constants'는 undefined가 됩니다.
✅ 해결 방법 3가지
✅ 방법 1. default → named export로 바꾸기 (가장 추천)
// colors.ts
export const colors = {
...
};
// index.ts
export * from './colors';
// 사용처
import { colors } from '@repo/constants';
✅ 가장 직관적이고 안전한 방식입니다.
✅ 방법 2. default export 유지하면서 export 이름 지정
// colors.ts
const colors = { ... };
export default colors;
// index.ts
export { default as colors } from './colors';
// 사용처
import { colors } from '@repo/constants';
✅ default export를 유지하면서도 named import처럼 쓸 수 있습니다.
⚠️ 방법 3. default import로 직접 경로 import (비추천)
import colors from '@repo/constants/colors';
⚠️ 경로를 직접 노출하게 되어 리팩토링이 어려워질 수 있습니다.
💡 결론
목적 추천 방식
import { colors } 하고 싶다 | export const colors = ... 사용 |
default export 꼭 유지하고 싶다 | export { default as colors } 추가 |
하위 경로로 import | 가능은 하지만 비추천 |
반응형
'programing > App' 카테고리의 다른 글
[React] key를 분명히 넣었는데도 Warning이 뜬다면? (Fragment 주의!) (0) | 2025.03.27 |
---|---|
[React Native/Expo] uuid 사용 시 crypto.getRandomValues() 에러 해결하기 (0) | 2025.03.26 |
React Native에서 Pressable vs TouchableOpacity: 어떤 걸 써야 할까? (1) | 2025.03.25 |
[React Native] TailwindCSS 전체 색상표를 React Native에 적용하기 (0) | 2025.03.25 |
[React Native] Tailwind 색상 시스템 구현하기 (다크모드 & 알파 포함) (0) | 2025.03.25 |