페블_
반짝이는 시냅스
페블_
전체 방문자
오늘
어제
  • 전체글 보기 (96)
    • QA (0)
    • 프로젝트 회고 (4)
    • 프로젝트 과정 기록 (12)
    • UI 구현 연구일지 (8)
    • Front-end (31)
      • Javascript (7)
      • CSS (10)
      • React (5)
      • Typescript (3)
      • Nextjs (3)
      • 스타일링 라이브러리 (3)
    • Back-end (0)
      • Express (0)
      • DB (0)
    • CS (0)
      • 자료구조 & 알고리즘 (0)
    • CI&CD (1)
    • 툴 사용법 (4)
      • Git (1)
      • Library&패키지 (2)
      • 기타 개발관련 (1)
    • 알고리즘 이론 & 풀이 (36)
      • 백준(BOJ) (14)
      • 프로그래머스 (22)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • storybook
  • 캐러셀
  • emotion
  • JS
  • 토이프로젝트
  • 백준
  • 생각
  • eslint
  • 개발블로그_시작
  • 선형대수학
  • 시리즈_표지
  • chartjs
  • Python
  • TypeScript
  • react
  • 파이썬
  • 알고리즘
  • UI 컴포넌트

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
페블_

반짝이는 시냅스

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

 

'Front-end > Typescript' 카테고리의 다른 글

[Typescript] React에서 type, interface는 어디에 정의하는게 좋을까?  (0) 2023.06.16
[Typescript] interface vs type  (0) 2023.05.29
    'Front-end/Typescript' 카테고리의 다른 글
    • [Typescript] React에서 type, interface는 어디에 정의하는게 좋을까?
    • [Typescript] interface vs type
    페블_
    페블_

    티스토리툴바