Front-end/Typescript

[Typescript] 이미 존재하는 CRA에 Typescript 추가하기

페블_ 2023. 6. 2. 15:14

CRA 생성할 때부터 Typescript 설정하기

npx create-react-app my-app --template typescript

 

이랬다면 좋겠으나... 때로는 CRA 설치하고 온갖 라이브러리 설정도 다 해놓은 다음에 Typescript 설정을 하지 않았다는 사실을 알고 멘붕이 오기도 한다. 그 때는 TS에 필요한 패키지와 설정을 추가로 해주면 된다.

 

 

이미 존재하는 CRA에 Typescript 추가하기

1. 패키지 설치

npm install --save typescript @types/node @types/react @types/react-dom @types/jest

 

2. 파일 확장자 .ts 혹은 .tsx로 바꾸기

jsx 문법을 사용하고 있던 파일은 .tsx로, 순수 js 파일은 .ts로 확장자를 바꾼다.

아직 프로젝트에 별 파일 생성하지 않은 초기 단계라면 App.tsx, index.tsx 정도로 바꾸면 될 것이다.

 

그리고 App.tsx에서 root 엘리먼트를 가져오는 부분에도 아래와 같이 HTMLElement로 타입을 부여해준다.

// App.tsx

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);

 

3. tsconfig.json 파일 생성하기

프로젝트 루트에 tsconfig.json 파일을 생성한다. Typescript를 컴파일할 수 있게 해주는 설정 파일이다.

아래는 적당한 기본 설정이다.

// tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src"],
  "exclude": [
    "node_modules"
  ]
}

 

Reference

필요한 패키지 설치 부분은 공식 문서를 참조함

 

Adding TypeScript | Create React App

Note: this feature is available with react-scripts@2.1.0 and higher.

create-react-app.dev

 

tsconfig.json 설정 출처는 아래의 스택오버플로우 게시글에서

https://stackoverflow.com/questions/48967495/adding-typescript-to-existing-create-react-app-app