Skip to content

Latest commit

 

History

History
244 lines (187 loc) · 8.44 KB

File metadata and controls

244 lines (187 loc) · 8.44 KB

TypeScript 사용하기

TypeScriptFlow와 비슷하게, JavaScript에 타입 정의를 추가한 JavaScript 확장판 언어입니다. React Native는 Flow에 내장되어 있지만, 기본적으로 TypeScript와 Flow 둘 다 지원합니다.

TypeScript 시작하기

몇 가지 다른 방법으로 새 프로젝트를 시작할 수 있습니다.

TypeScript 템플릿을 사용할 수 있습니다.

npx react-native init MyApp --template react-native-template-typescript

참고: 위의 명령이 실패할 경우, react-nativereact-native-cli 의 이전 버전이 시스템에 전역으로 설치되어 있을 수 있습니다. 문제를 해결하려면 CLI를 제거해 보십시오.

  • npm uninstall -g react-native-cli 또는 yarn global remove react-native-cli

그리고 나서 npx 명령을 다시 실행해보세요.

두 개의 TypeScript 템플릿이 있는 Expo를 사용할 수 있습니다.

  • npm

    npm install -g expo-cli
    expo init MyTSProject
  • Yarn

    yarn global add expo-cli
    expo init MyTSProject

또는 마찬가지로 TypeScript 템플릿이 있는 Ignite를 사용할 수도 있습니다.

  • npm

    npm install -g ignite-cli
    ignite new MyTSProject
  • Yarn

    yarn global add ignite-cli
    ignite new MyTSProject

기존 프로젝트에 TypeScript 추가하기

  1. TypeScript와 React Native의 types, Jest를 프로젝트에 추가하세요.
  • npm

    npm install -D typescript @types/jest @types/react @types/react-native @types/react-test-renderer
  • Yarn

    yarn add -D typescript @types/jest @types/react @types/react-native @types/react-test-renderer
  1. TypeScript 설정 파일을 추가하세요. 프로젝트 루트에 tsconfig.json 를 생성합니다.
{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react",
    "lib": ["es6"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext"
  },
  "exclude": [
    "node_modules",
    "babel.config.js",
    "metro.config.js",
    "jest.config.js"
  ]
}
  1. TypeScript를 사용하기 위해 jest.config.js 파일을 생성합니다.
module.exports = {
  preset: 'react-native',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
};
  1. JavaScript 파일(*.js)들의 확장자를 *.tsx 로 변경합니다.

진입점(entrypoint) 파일 ./index.js 는 그대로 두어야 합니다. 그렇지 않으면 프로덕션 빌드를 번들링할 때 문제가 발생할 수 있습니다.

  1. yarn tsc 를 실행해 새로운 TypeScript 파일들의 타입 체크를 합니다.

TypeScript와 React Native의 작동 방식

파일을 JavaScript로 즉시 변환하는 작업은 TypeScript가 아닌 React Native 프로젝트와 동일한 Babel 인프라를 통해 작동합니다. TypeScript 컴파일러는 타입 체킹에만 사용하는 것을 권장합니다. 기존 TypeScript 코드를 React Native로 포팅한 경우, TypeScript 대신 Babel을 사용할 때 한 두가지 주의사항이 있습니다.

React Native + TypeScript 예시

JSX로 컴포넌트를 작성할 때 에디터 자동완성 기능과 타입체크 기능을 제공하는 React.Component<Props, State> 를 통해, React 컴포넌트의 PropsState에 대한 인터페이스를 제공할 수 있습니다.

components/Hello.tsx

import React from 'react';
import { Button, StyleSheet, Text, View } from 'react-native';

export type Props = {
  name: string;
  baseEnthusiasmLevel?: number;
};

const Hello: React.FC<Props> = ({
  name,
  baseEnthusiasmLevel = 0
}) => {
  const [enthusiasmLevel, setEnthusiasmLevel] = React.useState(
    baseEnthusiasmLevel
  );

  const onIncrement = () =>
    setEnthusiasmLevel(enthusiasmLevel + 1);
  const onDecrement = () =>
    setEnthusiasmLevel(
      enthusiasmLevel > 0 ? enthusiasmLevel - 1 : 0
    );

  const getExclamationMarks = (numChars: number) =>
    numChars > 0 ? Array(numChars + 1).join('!') : '';

  return (
    <View style={styles.container}>
      <Text style={styles.greeting}>
        Hello {name}
        {getExclamationMarks(enthusiasmLevel)}
      </Text>
      <View>
        <Button
          title="Increase enthusiasm"
          accessibilityLabel="increment"
          onPress={onIncrement}
          color="blue"
        />
        <Button
          title="Decrease enthusiasm"
          accessibilityLabel="decrement"
          onPress={onDecrement}
          color="red"
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  },
  greeting: {
    fontSize: 20,
    fontWeight: 'bold',
    margin: 16
  }
});

export default Hello;

TypeScript playground에서 더 자세한 문법을 확인할 수 있습니다.

유용한 정보를 찾을 수 있는 곳

TypeScript와 함께 사용자 정의 경로 Alias 사용하기

TypeScript와 함께 사용자 정의 경로 alias를 사용하려면, Babel 및 TypeScript에서 모두 작동할 경로 alias를 설정해야 합니다. 방법은 다음과 같습니다.

  1. tsconfig.json 을 수정해 사용자 정의 경로 매핑을 사용합니다. src 루트의 모든 항목을 이전 경로의 참조 없이 사용할 수 있도록 설정하고, tests/File.tsx 를 사용해 모든 테스트 파일에 접근할 수 있도록 합니다.

        "target": "esnext",
    +     "baseUrl": ".",
    +     "paths": {
    +       "*": ["src/*"],
    +       "tests": ["tests/*"],
    +       "@components/*": ["src/components/*"],
    +     },
        }
  2. 프로젝트 개발 패키지로 babel-plugin-module-resolver를 추가합니다.

  • npm

    npm install --save-dev babel-plugin-module-resolver
  • Yarn

    yarn add --dev babel-plugin-module-resolver
  1. 마지막으로, babel.config.js 를 설정하세요 (babel.config.js 의 문법은 tsconfig.json 과 다릅니다).
{
  plugins: [
+    [
+       'module-resolver',
+       {
+         root: ['./src'],
+         extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
+         alias: {
+           tests: ['./tests/'],
+           "@components": "./src/components",
+         }
+       }
+    ]
  ]
}