[TS] React 프로젝트 JS -> TS로 변환하기
Typescript
Typescript는 Javascript의 변수에 형식을 지정한 파생 언어이다.
Typescript로 변환하기 앞서 아래의 문서로 기본 구조를 먼저 익히자.
https://yamoo9.gitbook.io/typescript/
TypeScript 가이드북 - TypeScript Guidebook
타입(Types)을 사용하면 JavaScript 애플리케이션을 개발할 때 정적 타입 검사 및 코드 리팩토링과 같은 생산성 높은 개발을 수행할 수 있습니다. 타입 설정이 필수는 아니지만, 설정할 경우 컴파일
yamoo9.gitbook.io
설치하기
https://create-react-app.dev/docs/adding-typescript/
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
or
yarn add typescript @types/node @types/react @types/reac-dom @types/jest
tsconfig.json 파일 생성
npx tsc --init
tsconfig 파일이 생성되면 allowJs 설정을 추가하자.
"compilerOptions": {
"allowJs": true
}
allowJs는 타입스크립트 컴파일 작업 시 자바스크립트 파일도 포함할 수 있는지 지정하는 옵션이다.
true or false 값으로 지정 가능하다.
그 외의 설정 값 참고 문서
https://www.typescriptlang.org/ko/tsconfig
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
이제 js로 작성된 파일 확장자를 js -> tsx를 변경해 준 뒤 점진적으로 적용하면 된다.
기존 프로젝트의 패키지중 일부는 업데이트나 @type 패키지를 필요로 할 수 있으니 하나씩 확인하며 진행해보자.
# Cannot find module '.Home.module.css' or its corresponding type declareations.
Home.js 파일을 Home.tsx 로 변경 뒤 발생한 에러.
css 모듈인 Home.module.css를 불러오지 못하고 있다.
해결방법
npm install @types/css-modules
@types/css-modules 패키지 설치해주기
# Cannot use JSX unless the '--jsx' flag is provided.
해결방법
tsconfig.json
"compilerOptions": {
// ...
"jsx": "react-jsx"
}
jsx 옵션은 jsx가 자바스크립트 파일에서 내보내지는 방식을 제어하는 옵션이다.