TypeScript는 Flow와 비슷하게, JavaScript에 타입 정의를 추가한 JavaScript 확장판 언어입니다. React Native는 Flow에 내장되어 있지만, 기본적으로 TypeScript와 Flow 둘 다 지원합니다.
몇 가지 다른 방법으로 새 프로젝트를 시작할 수 있습니다.
TypeScript 템플릿을 사용할 수 있습니다.
npx react-native init MyApp --template react-native-template-typescript참고: 위의 명령이 실패할 경우,
react-native나react-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와 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
- 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"
]
}- TypeScript를 사용하기 위해
jest.config.js파일을 생성합니다.
module.exports = {
preset: 'react-native',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
};- JavaScript 파일(
*.js)들의 확장자를*.tsx로 변경합니다.
진입점(entrypoint) 파일
./index.js는 그대로 두어야 합니다. 그렇지 않으면 프로덕션 빌드를 번들링할 때 문제가 발생할 수 있습니다.
yarn tsc를 실행해 새로운 TypeScript 파일들의 타입 체크를 합니다.
파일을 JavaScript로 즉시 변환하는 작업은 TypeScript가 아닌 React Native 프로젝트와 동일한 Babel 인프라를 통해 작동합니다. TypeScript 컴파일러는 타입 체킹에만 사용하는 것을 권장합니다. 기존 TypeScript 코드를 React Native로 포팅한 경우, TypeScript 대신 Babel을 사용할 때 한 두가지 주의사항이 있습니다.
JSX로 컴포넌트를 작성할 때 에디터 자동완성 기능과 타입체크 기능을 제공하는 React.Component<Props, State> 를 통해, React 컴포넌트의 Props와 State에 대한 인터페이스를 제공할 수 있습니다.
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 핸드북
- React의 TypeScript 관련 문서
- React + TypeScript 치트시트는 TypeScript를 React와 함께 사용하는 방법에 대한 좋은 개요를 제공합니다.
TypeScript와 함께 사용자 정의 경로 alias를 사용하려면, Babel 및 TypeScript에서 모두 작동할 경로 alias를 설정해야 합니다. 방법은 다음과 같습니다.
-
tsconfig.json을 수정해 사용자 정의 경로 매핑을 사용합니다.src루트의 모든 항목을 이전 경로의 참조 없이 사용할 수 있도록 설정하고,tests/File.tsx를 사용해 모든 테스트 파일에 접근할 수 있도록 합니다."target": "esnext", + "baseUrl": ".", + "paths": { + "*": ["src/*"], + "tests": ["tests/*"], + "@components/*": ["src/components/*"], + }, }
-
프로젝트 개발 패키지로 babel-plugin-module-resolver를 추가합니다.
-
npm
npm install --save-dev babel-plugin-module-resolver
-
Yarn
yarn add --dev babel-plugin-module-resolver
- 마지막으로,
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",
+ }
+ }
+ ]
]
}