넥스트(Next.js)에 타입스크립트(TypeScript) 환경 설정 하는 방법

2021. 10. 25. 17:30카테고리 없음

설치 순서

 

- Next.js 환경 설치

  1. npm init next-app 또는 yarn create next-app
    프로젝트명 입력
    설치 완료 확인
  2. npm run dev 또는 yarn dev
    http://localhost:3000/ 화면 출력 확인

- 타입 스크립트 환경 설정

  1. npm install --save-dev typescript @types/react @types/node 또는
    yarn add --dev typescript @types/react @types/node
  2. /pages/_app.tsx 파일 생성 후 코드 작성
    // /pages/_app.tsx
    
    import { AppProps } from 'next/app';
    
    function App({ Component, pageProps }: AppProps) {
        return <Component { ...pageProps } />;
    }
    
    export default App;
  3. 프로젝트 중지 후 재실행 
    npm run dev 또는 yarn dev
    tsconfig.json 파일 생성 확인
  4. index.js -> index.tsx로 파일명 변경 후 코드 수정
    // /pages/index.tsx
    
    import React, { useState } from "react";
    
    export default function Home() {
        const [text, setText] = useState < string > ("JavaScript");
    
        setTimeout(() => {
            setText("TypeScript");
        }, 1000);
    
        return (
            <div className="container">
                <div>
                    <span>{text} 적용 완료</span>
                </div>
            </div>
        );
    }​
    http://localhost:3000/ 화면 출력 확인
  5. 타입스크립트에서 styled-components 사용하는 경우 아래 패키지 설치하면 기존과 동일하게 사용 가능
    npm install --save-dev @types/styled-components