很长一段时间就想把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 每日更新前端技术