很長一段時間就想把ts引入公司的項目,但老是由於一些緣由被擱置。接下來有機會重構以前的rn項目,藉此機會正好能夠引入ts,爲了使後期的項目架構更加完善,近期我會梳理rn的一些知識點和新特性。html
首先來介紹下TypeScript前端
具體看官網傳送門,畢竟今天的重點在如何使用node
react-native init TSReactNativeDemo
項目結構react
├── App.js ├── __tests__ ├── android ├── app.json ├── index.js ├── ios ├── node_modules ├── package.json └── yarn.lock
而後測試下新建的項目是否能運行android
react-native run-android react-native run-ios
因爲React Native Packager是經過Babel編譯.js文件以及打包的,因此沒辦法直接使用.tsx。折中本思路就是,先用TypeScript的編譯器tsc將.ts或.tsx文件編譯成.js文件,再用React Native Packager編譯打包便可。ios
首先咱們安裝TS依賴:typescript
yarn add -D typescript
而後須要安裝types:npm
yarn add -D @types/react @types/react-native
而後須要配置tsconfig.json,能夠用以下命令生成:json
tsc --init --pretty --sourceMap --target es2015 --outDir ./lib --rootDir ./ --module commonjs --jsx react
生成的文件裏面有具體每一個參數的含義,也能夠參考TS官網文檔。react-native
仍是同樣的面孔,仍是那個讓咱們魂牽夢繞的栗子—計數器(Counter.tsx)
import * as React from 'react'; import { Button, StyleSheet, Text, View } from 'react-native'; interface Props { name: string; count?: number; onInc?: () => void; onDec?: () => void; } export default ({ name, count = 1, onInc, onDec }: Props) => ( <View style={styles.root}> <Text> Counter {name}: {count} </Text> <View> <Button title="+" onPress={onInc || (() => {})} /> <Button title="-" onPress={onDec || (() => {})} /> </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', }, });
接下來就是利用ts編譯器編譯寫好的.tsx我的建議在package.json中配置一下
... "scripts": { "start": "node node_modules/react-native/local-cli/cli.js start", "tsx":"./node_modules/.bin/tsc", "test": "jest" }, ...
而後執行
npm run tsx
因爲ts默認的tsconfig.json中設置了
"outDir": "./lib"
因此在項目根目錄/lib下會生成編譯後的.js文件如
lib └── src ├── Counter.js └── Counter.js.map
最後一步就是在入口js中引用編譯後的文件,而後打包測試便可。
總體看來,ts的引入讓咱們前期多了幾步操做,但這些問題均可以在自動化打包部署中用腳本幫咱們完成,另外對於ts不熟悉,一些習慣了js弱類型的開發者來講這樣的寫法無疑就是沒事找事。我不反駁這種觀點,舉幾個例子
interface Props { onInc?: () => void; } ... <View> <Button title="+" onPress={onInc || (() => {})} /> ...
若是我這裏沒有規定onInc爲可爲空且無返回值的fun,而且在onPress中沒有作undefind判斷,頁面在使用這個子組件的時候一旦傳入的值是undefind就會致使奔潰。若是這些功能一我的作還好,多人協做,這樣本能夠避免的問題就會被無限放大。
ts的引入能夠下降項目的維護成本,做爲企業級的項目這是頗有必要的
可能有人會拿ts和flow作比較,首先兩者我都有使用過,整體的感受ts更強大一點,我的建議仍是使用ts
文章可能有不少不足的地方,但願你們指正,同時也但願你們能夠多多交流,分享出更多的技術方案,謝謝~~
技術交流羣:581621024 關注小編 公衆號:LearningTech 每日更新前端技術