반응형
250x250
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

짧은코딩

React + Typescript + Vite + yarn berry + Tailwind css 세팅하기 본문

UpLog 릴리즈노트 프로젝트

React + Typescript + Vite + yarn berry + Tailwind css 세팅하기

5_hyun 2023. 7. 9. 20:51

이번에 진행하는 프로젝트는 webpack, npm이 아닌 viteyarn berry를 사용하는 과제를 받았다.

이 글에서 설명하는 초기 세팅은 react, ts, vite, yarn berry, tailwind css + twin.macro(emotion js), recoil, react query, jest, cypress를 설치하는 과정이다!(뭔가 엄청 많다..)

먼저 짧은 후기를 적어보자면 vite에 대한 정보가 너무 없어서 좀 힘겨웠다..!


Vite + React + yarn berry 적용

yarn create vite

먼저 이 명령어를 입력하고 react, typescript를 각각 선택해줬다.

yarn berry 전환

yarn set version berry

pnp 모드 적용

  1. 먼저 .yarnrc.yml 파일에서 nodeLinker: “node_modules”로 하고 yarn install 실행
  2. 바로 nodeLinker: “pnp”로 바꾸고 yarn install 실행, 이러면 node_modules가 사라짐
  3. yarn dev를 하여 실행하면 node_modules가 다시 생김

의문점

  • pnp는 zero install인데 node_modules가 생겨도 괜찮은가?

        => yarn 패키지 매니저를 통해 외부 패키지 사용시 해당 소스 코드 등은 node_modules에 생기기 때문에 있어도 된다!


Tailwind css + Twin.macro(emotion.js)

tailwind css는 https://tailwindcss.com/docs/guides/vite 공식 문서 보고 설치!
Twin.macro(emotion js)도 https://github.com/ben-rogerson/twin.examples/tree/master/vite-emotion-typescript#installation

공식 깃허브를 보고 설치!

(+ 추가적으로 @babel/core 설치해야됨)
(+ reset css 적용)

eslint, prettier

https://velog.io/@limelimejiwon/ReactViteESLintPrettier-설정하기

 

React+Vite+ESLint+Prettier 설정하기

Prettier, ESLint를 배우고 코드 가독성을 위한 관리가 필수라는 걸 깨달았다. 내 코드를 읽는 다른 사람을 위해서도 코드를 작성하는 나를 위해서도 적절한 포맷팅이 필요하기 때문에! ESLint와 Prettie

velog.io

이 블로그 설치! 글쓴이분께 매우 감사!!

Recoil, React-query, axios 

yarn add recoil
yarn add @tanstack/react-query
yarn add axios

+ react query devtool 설치!


JEST

yarn add @testing-library/react @testing-library/user-event @testing-library/jest-dom @types/testing-library__jest-dom

중간중간 에러들

  • jest에서 빨간 줄 나는거 해결

https://stackoverflow.com/questions/50863312/jest-gives-cannot-find-module-when-importing-components-with-absolute-paths

 

Jest gives `Cannot find module` when importing components with absolute paths

Receiving the following error when running Jest Cannot find module 'src/views/app' from 'index.jsx' at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17) at Object.<

stackoverflow.com

package.json에 경로 설정이 안되어 있어서 그런거 같음

 

  • 인텔리제이 에러

이 경고는 인텔리제이에서만 나는 경고라서 크게 신경쓰지 않아도 된다함https://www.inflearn.com/questions/491936/mapmutations-적용-시-method-expression-is-not-of-function-type-warning-발생-관련하여-문의-드

 

mapMutations 적용 시 Method expression is not of Function type Warning 발생 관련하여 문의 드립니다. - 인프런 |

질문 1안녕하세요! 강의 재미있게 잘 보고 있습니다. 양질의 강의에 감사드립니다.mapMutations 적용 실습 도중 'Method expression is not of Function type' warning이 발생하여 문의 드립니다.소스가 예시와 완

www.inflearn.com

  • TypeError: (0 , _globals.expect)(...).toBeInTheDocument is not a function

이 에러가 떠서 아래 스택 오버 플로우 보고 해결함

https://stackoverflow.com/questions/56547215/react-testing-library-why-is-tobeinthedocument-not-a-function

 

react-testing-library why is toBeInTheDocument() not a function

Here is my code for a tooltip that toggles the CSS property display: block on MouseOver and on Mouse Out display: none. it('should show and hide the message using onMouseOver and onMouseOut events

stackoverflow.com

 

이후 설정들

  • package.json
"test": "react-scripts test --watchAll",
"test:coverage": "yarn test --coverage --watchAll",

이렇게 명령어 추가 했는데 react-scripts가 없어서 yarn add 함

  • src/tests/utils.tsx
import {MemoryRouter, Routes} from "react-router-dom";

export function withRouter(routes: JSX.Element, initialEntry: string = "/"): JSX.Element {
    return (
        <MemoryRouter initialEntries={[initialEntry]}>
            <Routes>{routes}</Routes>
        </MemoryRouter>
    );
}

빨간 줄은 뜨지만 이렇게 해서 모든 JEST 설정 완료!(실행은 잘됨)


Cypress

yarn add --dev cypress-vite
yarn add -D cypress
yarn add -D @testing-library/cypress

 

-cypress.config.ts

const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    supportFile:false,
    baseUrl: 'http://localhost:3070',
  },
})

https://github.com/mammadataei/cypress-vite

 

GitHub - mammadataei/cypress-vite: Run Cypress specs using Vite

Run Cypress specs using Vite. Contribute to mammadataei/cypress-vite development by creating an account on GitHub.

github.com

공식 사이트 보고 함

신기한게 ts 파일인데 js꺼로 해도 에러는 안남..!

 

-tsconfig.json

"types": ["cypress", "node","@testing-library/cypress"],

"@testing-library/cypress" 이거 추가!

https://testing-library.com/docs/cypress-testing-library/intro/

 

Cypress Testing Library | Testing Library

Cypress Testing Library allows the use of dom-testing queries within

testing-library.com

마찬가지로 공식사이트 보고함!

 

잘 실행됨!


일단 위 과정까지 하고 실행했을 때는 문제가 없었지만 build 과정에서 에러가 엄청났었다...

여기는 build에서 에러 해결 과정!

build 시 생기는 에러 해결 과정

yarn build를 하면 위와 같은 에러가 발생함

 

  • tsconfig.json
{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true
  }
}

저 속성을 추가해야 내보내기가 없는 모듈을 있는 것처럼 처리할 수 있다.

  • package.json
// "jsxImportSource": "@emotion/react",
"jsx": "react-jsx",

기존에 있던 jsxImportSource를 없앰

  • 'X' is declared but its value is never read in TypeScript
"noUnusedLocals": false,
"noUnusedParameters": false,

사용되지 않는 변수가 있을 때, 에러가 났는데 위 2개의 속성을 설정해서 해결했음

 

  • error TS2339: Property 'toBeInTheDocument' does not exist on type 'Matchers<void, HTMLElement> & SnapshotMatchers<void, HTMLElement> & Inverse<JestMatchers<void, HTMLElement>> & PromiseMatchers<...>'.

이 에러는 tsconfig.json에서

"exclude": [
    "*/**/*.test.tsx"
  ]

이 코드를 추가해서 고쳤다.


이로써 모든 기초 설정을 완료했다!

익숙하지 않은 환경을 설정하는 것이 너무 힘들었다. 그래도 나름 공식 문서를 많이 참고해서 해결한 것 같다.(공식문서 짱짱)

실행도 잘되고 빌드도 잘되지만 가끔 빨간줄이 생기는 경우가 꽤 있다. 이 부분에 대해서도 좀 더 공부하고 해결해봐야 겠다고 생각한다...!

중간중간 글에 설명을 적지 않은 부분이 몇 개 있지만 그 부분들은 구글링하면 쉽게 해결할거라고 생각한다!

혹시 누군가 이 글을 보고 세팅을 한다면 미리 고생하라고 하고싶다..! 화이팅!

728x90
반응형
Comments