[Typescript] Next.js + Typescript 초기 설정

Yang Sooho·2025년 4월 14일
post-thumbnail

Next.js 프로젝트에 TypeScript를 적용하면 더 안전하고 유지보수하기 쉬운 코드를 작성할 수 있으며,
이 포스트에서는 Next.js에서 TypeScript 환경을 처음 설정하는 방법을 단계별로 정리.

1. Next.js 프로젝트 생성

npx create-next-app@latest my-app
cd my-app

이미 프로젝트가 있다면 그 디렉토리로 이동.

2. Typescript 패키지 설정

npm install --save-dev typescript @types/react @types/node

자동으로 TypeScript 설정 파일을 생성.
tsconfig.json은 처음 실행할 때 자동으로 생성됨.

3. 파일 확장자 변경

  • 기존의 .js, .jsx 파일을 .ts, .tsx로 변경.

예시:

  • pages/index.js → pages/index.tsx
  • components/Button.jsx → components/Button.tsx

주의: .tsx는 JSX 문법이 들어간 파일에서만 사용.

4. tsconfig.json 자동 생성

다음 명령어를 실행하면 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로 수정.

5. 타입 정의 파일 확인

Next.js는 자동으로 next-env.d.ts 파일을 생성:

/// <reference types="next" />
/// <reference types="next/types/global" />
/// <reference types="next/image-types/global" />

이 파일은 삭제 금지, 타입 정의가 깨지면 컴파일 오류가 발생할 수 있음.

6. TypeScript 사용 예시

컴포넌트에서 type 정의

type ButtonProps = {
  label: string;
  onClick?: () => void;
};

const Button = ({ label, onClick }: ButtonProps) => {
  return <button onClick={onClick}>{label}</button>;
};

7. 자주 사용하는 타입 패키지

@types/react : React 관련 타입
@types/node : Node.js 관련 타입
@types/uuid, @types/lodash 등: 서드파티 라이브러리 타입

8. ESLint와 함께 쓰기

  • 코드 품질을 유지하려면 ESLint 설정도 같이 설정.
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"
  ]
}

9. 절대경로 설정

tsconfig.json에 다음 항목을 추가하면 @/components/Button처럼 경로를 쉽게 사용할 수 있음:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}

app 폴더를 src/app으로 옮겨두면 디렉토리도 더 깔끔해짐.

정리

이제 Next.js 프로젝트에서 TypeScript를 안전하게 사용할 준비 완료

정리하자면:

  • 타입 안정성 덕분에 코드 퀄리티가 상승
  • 초기 설정만 잘 하면 유지보수는 훨씬 쉬움
  • 협업 시 커뮤니케이션 비용 감소
profile
개발 한웅큼 메모 한 스푼

0개의 댓글