[React Native with TS] 타입스크립트로 리액트네이티브 boilder plate 만들기 (1)리액트 네이티브 앱 Typescript 로 세팅하기

라흐리·2021년 1월 17일
0
post-thumbnail

이 글은 https://medium.com/@vdelacou/set-up-react-native-app-with-typescript-6c775e512336 을 보고 작성되었습니다.

이번 주 목표는 기존에 JS 로 작성하고 있던 주식앱을 TS 로 마이그레이션 하는 것이다.

원래 기존 프로젝트 코드를 TS 로 탈바꿈 하려고 했으나... 온갖 빨간줄과 버그와 혈투끝에 앱도 정상적으로 작동되게 하지 못하고 저버렸다.

몇시간의 삽질 끝에 깃을 다시 원복하고 이럴거면 아예 새로 보일러플레이트를 만들어보는게 낫겠다 싶었다.

적당한 블로그를 찾아 그대로 따라해보았다.

우선 총 4단계로 진행될 것이다.

1단계: 리액트 네이티브 앱 Typescript 로 세팅하기 (React Native set JS to TS)
2단계: 리액트 네이티브 백터아이콘 설치하기(Add React Native Vector Icons)
3단계: 리액트 네비게이션 설치 및 구현하기(Add React Navigation)
4단계: 리액트 네이티브 앱에 리덕스 스토어 붙이기

이번 포스팅은 1단계 세팅 부분을 다루겠다.

1단계. 리액트 네이티브 앱 Typescript 로 세팅하기 (React Native set JS to TS)

(1) 타입스크립트로 세팅된 RN 앱 설치

react-native init myapp --template typescript

(2) ts lint 설치

npm install tslib tslint tslint-react tslint-config-standard tslint-config-prettier tslint-react-hooks tsutils tslint-etc --save-dev

(3) 루트 경로에 tslint.json 생성하여 린트 파일 설정하기 (본인의 스타일에 맞게 커스텀하면 된다)

{
  "extends": [
    "tslint:recommended",
    "tslint-config-standard",
    "tslint-etc",
    "tslint-react",
    "tslint-react-hooks",
    "tslint-config-prettier"
  ],
  "rules": {
    // types related rules
    "no-inferrable-types": true,
    "no-namespace": {
      "options": ["allow-declarations"]
    },
    "interface-name": {
      "options": "never-prefix"
    },
    "no-unsafe-any": true,
    // core lint rules
    "ban": {
      "options": [
        {
          "name": "parseInt",
          "message": "use #type-coercion -> Number(val)"
        },
        {
          "name": "parseFloat",
          "message": "use #type-coercion -> Number(val)"
        },
        {
          "name": "Array",
          "message": "use #array-constructor"
        },
        {
          "name": ["describe", "only"],
          "message": "don't focus spec blocks"
        },
        {
          "name": ["it", "only"],
          "message": "don't focus tests"
        }
      ]
    },
    "no-require-imports": true,
    "no-boolean-literal-compare": true,
    "no-invalid-this": {
      "options": "check-function-in-method"
    },
    "no-invalid-template-strings": true,
    "ordered-imports": true,
    "prefer-template": true,
    "newline-before-return": true,
    "match-default-export-name": true,
    "no-parameter-reassignment": true,
    "file-name-casing": [true, "kebab-case"],
    "switch-default": true,
    // tslint:recommended overrides
    "no-any": true,
    "member-access": {
      "options": ["no-public"]
    },
    "object-literal-sort-keys": false,
    "interface-over-type-literal": false,
    // tslint:tslint-config-standard overrides
    //
    // tslint-etc rules
    "no-unused-declaration": true,
    "no-missing-dollar-expect": true,
    "no-assign-mutated-array": true,
    // tslint-react rules
    "jsx-boolean-value": {
      "options": "never"
    }
  },
  // apply the same rules for any JS if allowJS is gonna be used
  "jsRules": true
}

(4) ./src 폴더 만들어서 App.tsx 파일 이동 후 클래스형에서 함수형 컴포넌트로 바꿔주기

import React, { FC } from "react";
import { Platform, StyleSheet, Text, View } from "react-native";
const instructions = Platform.select({
  ios: `Press Cmd+R to reload,\n Cmd+D or shake for dev menu`,
  android: `Double tap R on your keyboard to reload,\n Shake or press menu button for dev menu`
});
const App: FC = () => {
  return (
    <View style={styles.container}>
      <Text style={styles.welcome}>Welcome to React Native!</Text>
      <Text style={styles.instructions}>To get started, edit App.tsx</Text>
      <Text style={styles.instructions}>{instructions}</Text>
    </View>
  );
};
export default App;
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  },
  welcome: {
    fontSize: 20,
    textAlign: "center",
    margin: 10
  },
  instructions: {
    textAlign: "center",
    color: "#333333",
    marginBottom: 5
  }
});

(5) 루트 경로의 index.js 내용 바꿔주기

  • {} 컬리브레이스가 있다면 빼주고 App 임포트 경로 바꿔주기

import App from './src/App';

(6) __test__ 폴더 내 App-test.js 파일명 app-test.tsx 로 바꿔주기, 안에 있는 App 임포트 경로도 맞게 수정

it 에 빨간줄과 함께 모듈이 없다는 경고가 나오면 npm i --save-dev @types/jest

(7) package.json 스크립트에 다음 명령어 추가

"lint": "tslint src/**/*.ts* --project tsconfig.json"

(8) 허스키 설치: npm install husky --save-dev

package.json 에 추가

"husky": {
    "hooks": {
      "pre-commit": "npm run lint",
      "pre-push": "npm run lint"
    }
  }

위의 과정을 거치면 이제 내 앱이 타입스크립트로 성공적으로 실행이 된다.

아래는 완성된 앱의 기본 UI다.

profile
아침에는 공부, 저녁에는 개발하는 개발자입니다.

1개의 댓글

comment-user-thumbnail
2022년 7월 30일

안녕하세요!
팀 클라썸의 Brand 입니다.

라흐리님의 블로그 글을 보고
아래의 제안을 드리고 싶어서 이렇게 댓글을 남깁니다.

강남역 도보 2분거리에 위치한 클라썸에서 React Native 앱 개발자를 채용하고 있습니다.(EO에서 유명했던 인터뷰 영상 기억하시나요?, 포브스 아시아 30세 이하 리더 30인에 선정된 이채린 대표가 이끄는 클라썸 입니다.)
EO 인터뷰 영상: https://www.youtube.com/watch?v=Cty3T3n5cP0&feature=emb_title

클라썸은 React Native로 안드로이드앱, iOS앱을 개발하고, TypeScript로 웹, 앱, 백엔드를 모두 개발하는 Series A 스타트업입니다. 스타트업의 극초기부터 M&A(넥스알), IPO(데브시스터즈)까지 이끌었던 개발 총괄님과 KAIST 출신의 개발자가 절반 이상일 정도로 인재 밀도가 높은 개발팀이 함께 일하고 있습니다.

현재 클라썸은 서울대, 연세대, KAIST, 삼성, LG인화원, 직방, 마켓컬리 등 전세계 32개국 6000여개 학교와 기업에서 사용 중입니다. 작년에 미국 실리콘밸리와 한국에서 Series A 투자를 유치하였고, 지난 분기에는 매출 4배를 달성하였습니다. ‘교육계의 슬랙'이라고 불리며 미국과 한국을 중심으로 빠르게 성장하고 있습니다.

구글 공인 세계적인 미래학자. 토마스 프레이 다빈치연구소 소장은 “2030년이 되면 온라인에서 세계 최고 규모의 회사는 이름을 들어보지 못한 교육회사가 될 것”이라고 예측했습니다. 매해마다 SaaS시장 및 온라인 교육시장 규모는 거대해지고 있고, 시장의 흐름이 클라썸에게도 매우 긍정적으로 흘러가고 있는 상황입니다.

클라썸 채용공고)
React Native 앱 개발 포지션
https://classum.career.greetinghr.com/o/12359

웹, 백엔드, AI관련 전직군 채용 포지션
careers.classum.com

혹시 괜찮으시다면, 시간 편하실 때 커피챗을 통해 클라썸에 대해 더 자세하게 소개 드리고자 합니다.
커피챗 언제든지 문의 주시고, 커피챗 전에도 궁금하신 점 있으시면 언제든지 편하게 연락 주세요. 감사합니다 :)

Brand
010-9139-5223
jsdalsee@gmail.com

답글 달기