
Next.js 프로젝트에 TypeScript를 적용하면 더 안전하고 유지보수하기 쉬운 코드를 작성할 수 있으며,
이 포스트에서는 Next.js에서 TypeScript 환경을 처음 설정하는 방법을 단계별로 정리.
npx create-next-app@latest my-app
cd my-app
이미 프로젝트가 있다면 그 디렉토리로 이동.
npm install --save-dev typescript @types/react @types/node
자동으로 TypeScript 설정 파일을 생성.
tsconfig.json은 처음 실행할 때 자동으로 생성됨.
.js, .jsx 파일을 .ts, .tsx로 변경.예시:
주의:
.tsx는 JSX 문법이 들어간 파일에서만 사용.
다음 명령어를 실행하면 Next.js가 자동으로 tsconfig.json을 생성:
npm run dev
실행 시, tsconfig.json이 없다면 다음과 같이 자동 생성:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
strict 모드를 꺼야 하는 경우에는 "strict": false로 수정.
Next.js는 자동으로 next-env.d.ts 파일을 생성:
/// <reference types="next" />
/// <reference types="next/types/global" />
/// <reference types="next/image-types/global" />
이 파일은 삭제 금지, 타입 정의가 깨지면 컴파일 오류가 발생할 수 있음.
컴포넌트에서 type 정의
type ButtonProps = {
label: string;
onClick?: () => void;
};
const Button = ({ label, onClick }: ButtonProps) => {
return <button onClick={onClick}>{label}</button>;
};
@types/react : React 관련 타입
@types/node : Node.js 관련 타입
@types/uuid, @types/lodash 등: 서드파티 라이브러리 타입
pm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
.eslintrc.json설정 예시
{
"parser": "@typescript-eslint/parser",
"extends": [
"plugin:@typescript-eslint/recommended",
"next/core-web-vitals"
]
}
tsconfig.json에 다음 항목을 추가하면 @/components/Button처럼 경로를 쉽게 사용할 수 있음:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
app 폴더를 src/app으로 옮겨두면 디렉토리도 더 깔끔해짐.
이제 Next.js 프로젝트에서 TypeScript를 안전하게 사용할 준비 완료
정리하자면: