TIL | React +Typescript set up

sik2·2021년 7월 20일
0

TypeScript

목록 보기
1/1

React +Typescript

  • Typescript 는 Javasciprt 의 superset 이다.

CRA install

  • CRA 공홈의 설치 방법을 따라해서 설치하자

https://create-react-app.dev/docs/adding-typescript/

npx create-react-app my-app --template typescript

# or

yarn create react-app my-app --template typescript

what is NPX?

  • npx는 새로운 패키지 관리 모듈이 아니다. npm v5.2 부터 새로추가된 편의도구
  • npm 레지스트에 올라가 있는 패키지를 쉽게 설치하고 관리하는 CLI 도구
  • npm => Package Manager(관리), npx = Package Runner(실행)

확장자

what is tsx?

  • js => javascript, ts => typescript 인거 처럼
  • jsx => javascript 문법사용하는 jsx, tsx => typescript 문법사용하는 tsx

tsconfig.json


{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "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"
  ]
}

compilerOptions

  • 컴파일 옵션 설정
"compilerOptions": {
    (...)
    "allowSyntheticDefaultImports": true, // Synthetic Import 강제하기
    (...)
    "noImplicitAny":false, // 타입 에러 끄기
  }

package.json


{
  "name": "typescript_react_fundametals",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "@types/jest": "^26.0.15",
    "@types/node": "^12.0.0",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "typescript": "^4.1.2",
    "web-vitals": "^1.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

what is @types ?

@types이 없다면

yarn add style-components

이후 tsx 파일에서 import를 해보면 에러가 터진다.

때문에 @type/라이브러리명 형식으로 설치 해야한다.

yarn add @types/style-components

유명한 라이브러리들은 대부분 @types을 제공한다.
혹시나 설치하려는 라이브러리가 @types 가 없다면 tsconfig.json > compilerOptions 에서 "noImplicitAny":false 설정을 해주면 된다.

  "compilerOptions": {
    (...중략)
    "jsx": "react-jsx",
    "noImplicitAny":false, // 타입 에러 끄기
  }

ref)
https://nomadcoders.co/react-for-beginners
https://react.vlpt.us/using-typescript/01-practice.html
https://webruden.tistory.com/275

profile
기록

0개의 댓글