Typescript 설치
- CRA 리액트와 같이 TS설치
npx create-react-app my-app --template typescript
or
yarn create react-app my-app --template typescript
- 기존 CRA 리액트가 존재할때 TS만 추가하기
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
or
yarn add typescript @types/node @types/react @types/react-dom @types/jest
tsconfig.json 생성
- npx typescript --init나 tsc --init해서 tsconfig.json 생성
- 환경설정을 밑처럼 작성해야 build시 ts => js로 컴파일 가능해짐
- compilerOptions
설정옵션 공식문서
include : 컴파일할 파일 경로 설정
exclude : 컴파일에서 제외하는 대상
compilerOptions : 컴파일할 때 적용되는 옵션들- target : 어떤 버전으로 컴파일할 것인지 작성
- module : 어떤 모듈 방식으로 컴파일할지 설정
{
"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로 확장자 변경
- index.js => index.tsx 파일명,내용 변경
에러
React 18이 나오면서 밑에껀 구버전이므로 콘솔에 에러
- ReactDOM.render 말고 대신에 createRoot 사용하라는 문구
// 에러 메시지
react-dom.development.js:86 Warning: ReactDOM.render is
no longer supported in React 18. Use createRoot instead.
Until you switch to the new API, your app will behave as
if it's running React 17
// 구버전
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
해결방법
- 1) 우리가 적용한 것 - ! 추가
콘솔창 에러링크를 클릭했을 때
createRoot(container!) if you use TypeScript문구에서
createRoot(content!)구조를 보고 ! 추가- TS는 createRoot안에서 null을 반환할 수 없는데,
!을 붙여서 null이 아닐때로 설정하는 것
- TS는 createRoot안에서 null을 반환할 수 없는데,
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root')!);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
- 2) 또 다른 방법 - as HTMLElement 추가
getElementById로 받는 객체 타입을 지정해서 TS가 데이터 타입을 알 수 있게 해줌.
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
- App.js => App.tsx 파일명,내용 변경
import React from 'react';
import './App.css';
const App: React.FC = () => {
return (
<div className="App">
Hello Typescript
</div>
);
}
export default App;
라이브러리
styled-components, redux, react-router-dom과 같은 라이브러리를 사용했다면 밑과 같은 에러문이 뜨는데
- styled-components
npm install --dev @types/styled-components
에러에서 설명하는 순서대로 @types/라이브러리 설치
eslint 설정
- 프로젝트에서 설치
npm install -D eslint
- 프로젝트 root폴더에서 입력
npx eslint --init
- eslintrc.json생성
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:import/recommended",
"plugin:jsx-a11y/recommended",
"plugin:prettier/recommended"
],
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": "latest",
"sourceType": "module"
},
"rules": {
"react/react-in-jsx-scope": 0,
"react/jsx-uses-react": 0
}
}
prettier 설정
- prettier 설치
npm install -D eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-prettier eslint-config-prettier
- eslint-plugin-import : ES6의 import, export 구문을 지원, 필수 플러그인
eslint-plugin-react : React 규칙이 들어있는 플러그인
eslint-plugin-react-hooks : React Hooks 규칙이 들어있는 플러그인
eslint-plugin-jsx-a11y : JSX요소의 접근성 규칙에 대한 정적 검사 플러그인 - root폴더에서 .prettierrc 생성
- 설정 옵션 참고 링크
리액트에서 TS사용하기
React와 React + TypeScript의 차이점
- React: 타입 선언 없이 자유롭게 코드를 작성
- React + TypeScript: 상태, 속성, 함수, 이벤트 등에 타입을 명시하여 코드의 안정성을 높인다!
// React
const [state, setState] = useState('initial value');
// React + TypeScript
const [state, setState] = useState<string>('initial value');
React.FC 있는 경우 단점
- 기본적으로 children 포함: 모든 컴포넌트가 children을 가질 필요가 없지만, React.FC 타입을 사용하면 children이 기본적으로 포함됩니다.
- defaultProps 문제: React.FC를 사용하면 defaultProps가 제대로 작동하지 않을 수 있습니다.
import React from 'react';
type GreetingsProps = {
name: string;
};
const Greetings: React.FC<GreetingsProps> = ({ name }) => (
<div>Hello, {name}</div>
);
export default Greetings;
React.FC 생략 및 화살표 함수 사용하지 않는 경우
- React.FC생략하면 defaultProps 제대로 작동
- 화살표 함수말고 function 키워드 사용가능
import React from 'react';
type GreetingsProps = {
name: string;
mark: string;
option?: string;
};
function Greetings({ name, mark }: GreetingsProps) {
return (
<div>
Hello, {name} {mark}
</div>
);
}
Greetings.defaultProps = {
mark: '!'
};
export default Greetings;
'프로그래밍 > TypeScript' 카테고리의 다른 글
[TypeScript] 선택적 매개변수와 기본 매개변수 (0) | 2024.07.18 |
---|---|
[TypeScript] 타입스크립트의 함수 정의와 타입 명시 (0) | 2024.07.17 |
[TypeScript] 변수 선언과 기본 타입 (2) | 2024.07.15 |
타입스크립트 공부 자료 (2) | 2024.07.14 |
[TypeScript] ORM 라이브러리 비교 (2) | 2024.07.12 |