Notice
Recent Posts
Recent Comments
Link
COCO World
[React/리액트] 새프로젝트와 기존 프로젝트에 타입스크립트(typescript) 적용하는 방법 본문
🥕 개요
- TS 라이브러리 설치하기
- tsconfig.json 생성하기
- 파일 확장자 변경하고, 코드 수정하기
- 기타 주의사항
🥕 TS 라이브러리 설치
- 리액트의 새로운 프로젝트(CRA)에서 TS 설치하기
# npm 버전
npm create-react-app my-app --template typescript
# yarn 버전
yarn create react-app my-app --template typescript
- 기존 리액트에 프로젝트가 존재하고, TS만 추가설치하기
# npm 버전
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
# yarn 버전
yarn add typescript @types/node @types/react @types/react-dom @types/jest
🥕 tsconfig.json 생성
1. compilerOptions
- include : 컴파일할 파일 경로 설정
- exclude : 컴파일에서 제외하는 대상
-compilerOptions : 컴파일할 때 적용되는 옵션들
- target : 어떤 버전으로 컴파일할 것인지 작성
- module : 어떤 모듈 방식으로 컴파일할지 설정
자세한 설정옵션 공식문서 참고하러 가기
TSConfig Reference - Docs on every TSConfig option
From allowJs to useDefineForClassFields the TSConfig reference includes information about all of the active compiler flags setting up a TypeScript project.
www.typescriptlang.org
- 기본 버전
{
"compilerOptions": {
"target": "es6", //어떤버전의 js로 컴파일할지 정의
"lib": [ //어떤 환경에서 사용하는지 정의(api자동완성 제공해줌)
"dom", //브라우저
"dom.iterable",
"esnext"
],
"baseUrl": "./src", // 추가된 것 ./src를 절대 경로로 지정
"allowJs": true, //ts안에서 js허용(js파일 import가능)
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [ //컴파일할 폴더 입력. src의 모든파일 확인함
"src"
],
"exclude": [
"node_modules"
],
}
🥕 파일 확장자 수정
- .jsx나 .js 확장자 파일 ➠ .tsx 확장자로 변경
- 변경 후 에러 처리
- document.getElementById('root')에 !(느낌표) 추가하기
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root')!);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
- App.tsx에서 내용 변경
- 선언한 것들 중에서 타입이 명시되어 있지 않을 경우, 에러로 뜨니 검토하기
🥕 주의사항
- 추가적인 라이브러리를 추가할 경우 기본적으로 타입스크립트타입으로 설치해야 한다.
- @types/라이브러리 로 설치 요망
기존 자바스크립트 예시
# npm
npm install -g yarn
# yarn
npm install styled-components
타입스크립트에서 라이브러리 적용 예시
# npm
npm install --dev @types/styled-components
# yarn
yatn add --dev @types/styled-components
'Front-End > React' 카테고리의 다른 글
[React/리액트] Input의 공백 입력값 onChange를 이용해 제거하기 (0) | 2023.08.09 |
---|---|
[React/리액트] Redux Saga에 대해 알아보자. (0) | 2023.08.04 |
[React/리액트] Redux의 개념과 특징, 그리고 사용 목적 (0) | 2023.06.13 |
[리액트/React] 상태 관리는 왜, 어떻게 하는가? (0) | 2023.06.11 |
[리액트/React] JSX(개념, 문법, 특징)에 대해 알아보자. (0) | 2023.05.29 |