Typescript ile React Native Geliştirme

React Native Kurulumu

Sisteminizde React Native CLI kurulu değil ise npm ile (yarn da olabilir) global bir şekilde kurulumumuzu gerçekleştiriyoruz.

npm install -g react-native-cli

React Native CLI'nin sistemde kurulu olduğuna emin olduktan sonra Typescript geliştirme ortamını hazırlamaya başlayalım.

React Native projesi oluşturalım.

react-native init react-native-with-typescript

react-native-with-typescript adlı bir proje React Native projesi oluşturduk. Üzerinde çalışacağımız App.js ve sonrasında kendi oluşturacağımız diğer componentlere ait dosyalar olacak. Oluşturulan projede Typescript ortamına ait hiçbir dosya göremeyeceksiniz. Hemen React Native için Typescript ortamını hazırlayalım.

Başlamadan önce önemli bir not bırakayım. React Native için kullanacağınız bir çok kütüphanede Typescript Definition dosyası olmayacaktır. Dolayısıyla intellisense desteği de alamayacaksınız. Araştırma sonucunda herhangi bir definition dosyası bulamadıysanız, o kütüphane için özel bir definition dosyası hazırlamalısınız. Type Safe geliştirme yapabilmek için bu şart.

To get the best experience in TypeScript, we want the type-checker to understand the shape and API of our dependencies. Some libraries will publish their packages with .d.ts files (type declaration/type definition files), which can describe the shape of the underlying JavaScript. For other libraries, we'll need to explicitly install the appropriate package in the @types/ npm scope.

Typescript Ortamını Hazırlama

Typescript geliştirmesi yaparken, sözdizimi standartlarına uymak için gerekli linter kütüphanelerini aşağıdaki npm komutunu kullanarak kuruyoruz.

npm install typescript tslint tslint-react tslint-eslint-rules react-native-typescript-transformer tslint-react-recommended --save-dev

Typescript konfigürasyon dosyamızı oluşturalım.

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "jsx": "react",
    "outDir": "./dist",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "skipLibCheck": true,
    "declaration": true,
    "noUnusedLocals": true
  },
  "exclude": [
    "node_modules"
  ]
}

React Native ve React'a ait type definition'ları aşağıdaki komut ile kuruyoruz.

npm install @types/react @types/react-native --save-dev 

React Native CLI için de bazı konfigürasyonlara ihtiyacımız olacak.

module.exports = {
  getTransformModulePath() {
    return require.resolve('react-native-typescript-transformer');
  },
  getSourceExts() {
    return ['ts', 'tsx', 'js', 'jsx'];
  }
}

Şimdi de React Native tarafından varsayılan olarak oluşturulan App.js bileşeni içeriğini type safe geliştirme yapabileceğimiz şekilde düzenleyelim. Proje ağacında yer alan App.js yerine App.tsx dosyası oluşturun ve aşağıdaki içeriği oluşturun.

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

export interface Props {
  name: string;
  enthusiasmLevel?: number;
}

interface State {
  enthusiasmLevel: number;
}

export class Hello extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);

    if ((props.enthusiasmLevel || 0) <= 0) {
      throw new Error('You could be a little more enthusiastic. :D');
    }

    this.state = {
      enthusiasmLevel: props.enthusiasmLevel || 1,
    };
  }

  onIncrement = () =>
    this.setState({enthusiasmLevel: this.state.enthusiasmLevel + 1});
  onDecrement = () =>
    this.setState({enthusiasmLevel: this.state.enthusiasmLevel - 1});
  getExclamationMarks = (numChars: number) => Array(numChars + 1).join('!');

  render() {
    return (
      <View style={styles.root}>
        <Text style={styles.greeting}>
          Hello{' '}
          {this.props.name +
            this.getExclamationMarks(this.state.enthusiasmLevel)}
        </Text>

        <View style={styles.buttons}>
          <View style={styles.button}>
            <Button
              title="-"
              onPress={this.onDecrement}
              accessibilityLabel="decrement"
              color="red"
            />
          </View>

          <View style={styles.button}>
            <Button
              title="+"
              onPress={this.onIncrement}
              accessibilityLabel="increment"
              color="blue"
            />
          </View>
        </View>
      </View>
    );
  }
}

// styles
const styles = StyleSheet.create({
  root: {
    alignItems: 'center',
    alignSelf: 'center',
  },
  buttons: {
    flexDirection: 'row',
    minHeight: 70,
    alignItems: 'stretch',
    alignSelf: 'center',
    borderWidth: 5,
  },
  button: {
    flex: 1,
    paddingVertical: 0,
  },
  greeting: {
    color: '#999',
    fontWeight: 'bold',
  },
});

Typescript ile React Native geliştirme ortamımızı oluşturmuş olduk.

İyi çalışmalar dilerim.