ReactNativeにTypeScriptを導入する
概要
前回の続きです。 できたてホヤホヤのプロジェクトにTypeScriptを導入する。
環境
- react v16.3.1
- react-native v0.55.2
- react-native-cli v2.0.1
依存モジュールのインストール
$ npm install -D \ typescript \ node-libs-react-native \ react-native-typescript-transformer \ @types/react \ @types/react-native \ @types/jest $ npm audit fix
tsconfigの設定
{ "compilerOptions": { "target": "ES2017", "module": "ES2015", "jsx": "react-native", "rootDir": "./src", "strict": true, "skipLibCheck": true, "noImplicitAny": true, "noImplicitThis": true, "alwaysStrict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "moduleResolution": "node", "baseUrl": "./", "esModuleInterop": true, }, "include": [ "src/**/*" ], "exclude": [ "node_modules" ] }
CLIにTransformをフックする
const extraNodeModules = require('node-libs-react-native') module.exports = { extraNodeModules, getTransformModulePath() { return require.resolve('react-native-typescript-transformer'); }, getSourceExts() { return ['ts', 'tsx']; } }
App.jsを書き換え
import { Component } from 'react'; import { StyleSheet, Text, View } from 'react-native'; export default class App extends Component { render() { return ( <View style={styles.container}> <Text>Open up App.js to start working on your app!</Text> <Text>Changes you make will automatically reload.</Text> <Text>Shake your phone to open the developer menu.</Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, });
$ rm App.js
実行
$ npm run start
$ npm run android