항상 자바스크립트로 리액트를 사용해보다 타입스크립트를 사용해보고자 타입스크립트에서 리액트를 한 번 시작해보려고 한다.
프로젝트 생성
우선 template를 typescript로 하여 CRA(create-react-app)를 해준다.
npx create-react-app appName --template=typescript
yarn create react-app appName --template=typescript
yarn berry 설정
yarn set version berry
yarn or yarn install
yarn berry로 설정해주면 .yarnrc.yml 파일이 생기는 것을 볼 수 있고 npm 의존성을 제거해주기 위해 node_modules와 lock 파일을 지워준다.
(프로젝트 폴더에서 node_modules를 지울 경우 오래 걸리기 때문에 아래 명령어로 node_modules를 지워주자)
rmdir node_modules /s
이후 .gitignore에 Zero Installs의 사용 여부에 따라 추가해주자.
Zero Installs를 간단히 말하면 모든 패키지를 git에 포함시켜 git clone만 해도 바로 실행시킬 수 있는 환경을 만들 수 있는 개념이다.
Zero Installs를 사용할 경우
.yarn/*
!.yarn/cache
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
Zero Installs를 사용하지 않을 경우
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
❌ 에러 발생
yarn berry까지 셋팅해주고 나면 index.tsx와 App.tsx에서 에러가 발생하는 것을 볼 수 있었다.
Cannot find module '모듈명' or its corresponding type declarations.
💡 에러 해결
typescript 버전 변경
yarn berry에서 typescript의 버전이 4.9.4 이상일 경우 4.9.3으로 변경해주어야 한다.
yarn remove typescript
yarn add typescript@4.9.3
VSCode Setting
typescript를 사용하기 위해서는 vscode에서 ZipFS 확장 프로그램을 설치하고 아래 명령어를 입력해주어야 한다.
yarn dlx @yarnpkg/sdks vscode
위 명령어를 입력하면 아래와 같은 메세지가 나오는데 Allow를 누르면 된다.
만약 메세지가 뜨지 않거나 메세지가 사라졌다면 command pallette(ctrl + shift + p)를 켜서 Typescript: Select Typescript Version...을 누르고 Use Workspace Version을 선택하면 된다.
❌ 에러 발생
이렇게 모듈을 찾을 수 없다는 에러를 해결해주니 새로운 에러가 발생했다 😂
Property 'toBeInTheDocument' does not exist on type 'JestMatchers< HTMLElement >'.
💡 에러 해결
jestmatchers< HTMLElement > 에서 toBeInTheDocument 메소드를 찾지 못해서 발생한 에러로 devDependencies에 @types/testing-library__jest-dom을 추가시켜주었더니 에러가 해결되었다.
yarn add -D @types/testing-library__jest-dom
이렇게 Yarn Berry를 사용한 Typescript + React 프로젝트 생성하기 끄읕 !