Fall in IT.

React Native Typescript 설정하는 방법 본문

프레임워크/React Native

React Native Typescript 설정하는 방법

D.Y 2018. 8. 5. 11:22


안녕하세요.


오늘은 React Native에 TypeScript를 설정하는 방법에 대해서 알아보도록 하겠습니다.



React Native TypeScript 설정방법


1. 프로젝트 생성
$ react-native init [project name]

2. 프로젝트 진입
$ cd [project name]

3. 타입스크립트 및 필요한 모듈 추가
$ yarn add --dev typescript
$ yarn add --dev react-native-typescript-transformer
$ yarn tsc --init --pretty --jsx react
$ yarn add --dev @types/react @types/react-native
// tsconfig.json에서 "allowSyntheticDefaultImports" 속성 주석 해제)

4. 리액트 네이티브 설정 추가
// rn-cli.config.js 파일 생성
$ touch rn-cli.config.js

// rn-cli.config.js에 아래 내용 추가
module.exports = {
    getTransformModulePath() {
          return require.resolve("react-native-typescript-transformer");
    },
    getSourceExts() {
          return ["ts", "tsx"];
    }
}

5. 기존의 JS 파일을 TS로 마이그레이션
// App.js 파일을 App.tsx 파일로 변경 
$ mv App.js App.tsx // (개발툴에서 변경해도 좋습니다. :D)

6. 타입스크립트 테스팅 설정
$ yarn add --dev ts-jest

// package.json 파일에 아래 내용 추가
"jest": {
  "preset": "react-native",
  "moduleFileExtensions": [
    "ts",
    "tsx",
    "js"
  ],
  "transform": {
    "^.+\\.(js)$": "/node_modules/babel-jest",
    "\\.(ts|tsx)$": "/node_modules/ts-jest/preprocessor.js"
  },
  "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
  "testPathIgnorePatterns": [
    "\\.snap$",
    "/node_modules/"
  ],
  "cacheDirectory": ".jest/cache"
}

7. git ignore 추가
// .gitignore 파일에 아래 내용을 추가합니다.
.jest/ // jest 제외

8. 타입체킹을 위한 모듈 설치
- 타입 체킹을 위해서 @types 모듈 설치가 필요합니다. 아래 참고.
$ yarn add --dev @types/jest @types/react @types/react-native @types/react-test-renderer

9. Hello Component 추가
// Hello.tsx
import React, { Component } from 'react';
import { Button, StyleSheet, Text, View } from 'react-native';

export interface Props {
    count: number
}

interface State {
    count: number
}

export default class Hello extends Component {
    state = {
        count: this.props.count    
    };

    onDecrement = () => {
        this.setState({
            count: this.state.count - 1
        });
    }   

    onIncrement = () => {
        this.setState({
            count: this.state.count + 1
        });
    }

    render(): JSX.Element {
        return (
            
                Hello world!!!
            
        )
    }
}

10. App.tsx에서 Hello Component 추가
// App.tsx
/**
 * Sample React Native TypeScript App
 * https://github.com/facebook/react-native
 *
 * @작성자. dy.lee
 */

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import Hello from './Hello';

export default class App extends Component {
  render() {
    return (
      
        Welcome to React Native TypeScript!
        
      
    );
  }
}

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,
  },
});

11. 완료!




결과

  • 실행 결과 화면



Github 주소



느낀점

  • Angular base의 Ionic Framework를 사용한 하이브리드앱을 만들다 처음으로 React Native 앱을 만들어 보았습니다.
  • 코도바나 아이오닉 같은 크로스플랩폼은 웹뷰를 이용하여 렌더링하지만, React Native의 경우 표준렌더링(안드로이드, iOS 고유 UI컴포넌트)을 사용해서 그런지 앱 동작 느낌은 네이티브 앱과 거의 일치하는 느낌이었습니다.
  • 네이티브와의 연동관련 자료도 많아서 어렵지않게 네이티브 기능(카카오 연동 등)을 연동할 수 있습니다.
  • expo와 같은 툴을 사용하면 간편하게 데모 앱을 만들어볼 수 있습니다.



참고


모두 즐거운 코딩하세요~



Comments