Next.js 15과 styled-components를 사용할 때 theme 자동완성이 되지 않는 이유는 주로 TypeScript 설정과 styled-components의 ThemeProvider 타입 지정 문제 때문이야. 해결 방법을 정리해줄게.
✅ 해결 방법
1. styled-components 타입 정의 추가
먼저 styled-components의 DefaultTheme 타입을 확장해야 해.
styled.d.ts 파일을 프로젝트의 @types 폴더나 src 폴더 안에 추가:
// src/styled.d.ts
import "styled-components";
declare module "styled-components" {
export interface DefaultTheme {
colors: {
primary: string;
secondary: string;
background: string;
text: string;
};
}
}
이렇게 하면 theme 객체의 자동완성이 가능해져.
2. ThemeProvider에 타입 적용
theme.ts 파일을 만들어서 theme을 정의하고, ThemeProvider에 적용:
// src/theme.ts
import { DefaultTheme } from "styled-components";
export const theme: DefaultTheme = {
colors: {
primary: "#0070f3",
secondary: "#ff4081",
background: "#ffffff",
text: "#333333",
},
};
그리고 ThemeProvider를 설정:
// src/pages/_app.tsx
import { ThemeProvider } from "styled-components";
import { theme } from "../theme";
import type { AppProps } from "next/app";
export default function App({ Component, pageProps }: AppProps) {
return (
<ThemeProvider theme={theme}>
<Component {...pageProps} />
</ThemeProvider>
);
}
3. styled-components가 theme을 인식하는지 확인
자동완성이 적용되었는지 확인하려면 styled-components 사용 코드에서 theme을 참조:
import styled from "styled-components";
const Button = styled.button`
background-color: ${({ theme }) => theme.colors.primary};
color: ${({ theme }) => theme.colors.text};
`;
export default Button;
여기서 theme.colors.primary에 자동완성이 되면 성공!
✅ 추가 설정 (타입스크립트 설정 확인)
tsconfig.json에서 types가 올바르게 설정되어 있는지도 확인:
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"moduleResolution": "node",
"types": ["styled-components"]
}
}
그래도 자동완성이 안 된다면 VSCode를 재시작하거나 node_modules를 삭제 후 재설치:
rm -rf node_modules package-lock.json && npm install
# 또는
rm -rf node_modules yarn.lock && yarn install
이 방법으로 해결될 거야. 🚀
'라이브러리' 카테고리의 다른 글
[react-dnd] 드래그앤드랍 시 최신 state를 가져오지 못하는 버그 (0) | 2025.02.09 |
---|---|
[Swiper] 리액트 스와이퍼 자동 재생 특정 횟수에서 멈추기 (0) | 2025.01.14 |
[Notistack] 알림 스택 라이브러리 notistack 사용방법 (0) | 2025.01.06 |