为什么要使用TypeScript

TypeScript是JavaScript的超集,扩展了JavaScript语法,并对JavaScript兼容,且具备JavaScript所没有的编译时类型检查接口枚举类型推断等诸多特性。因此使用TypeScript进行程序编写大大减少运行时异常提升程序的稳定性。

更多TypeScript语法可参考《TypeScript

初始化一个RN项目

react-native init projectName

安装TypeScript相关插件

#RN Jest单元测试框架(具体使用,参考文末扩展)
yarn add --dev @types/jest @types/react-test-renderer

#typescript支持RN工具包
yarn add --dev typescript @types/react @types/react-native

创建TypeScript配置文件tsconfig.json

tsc --init

如果出现tsc:command not found则先进行typescript的安装

npm install -g typescript

配置tsconfig.json

{
  "compilerOptions": {
    "target": "es6", 
    "module": "commonjs",                  
    "lib": [
      "es2015.promise",
      "es2015",
      "es2016",
      "dom"
    ],
    "jsx": "react",                          
    "sourceMap": true,                       
    "outDir": "./lib",                           
    "strict": true,                           
    "esModuleInterop": true,                 
    "forceConsistentCasingInFileNames": true  
  }
}

更多esconfig.json配置参数见官网完整的编译器选项列表

创建.ts/.tsx文件编译并运行

  • 创建.ts类型接口及类

    IPerson.ts

    //IPerson 接口
    export interface IPerson{
      	age:number;
      	name:string;
      	getInfo():string;
    }
    

    PersonImpl.ts

    //PersonImpl实现类
    import {IPerson} from './IPerson'; //导入IPerson模块
    export class PersonImpl implements IPerson{
      	age:number;
      	name:string;
        //构造函数对变量初始化
        constructor(age:number,name:string){
          this.age = age;
          this.name = name;
        }
      
        //实现接口的getInfo方法
      	getInfo():string{
          return `print info name = ${this.name},age = ${this.age}`;
        }
    }
    
  • 创建组件.tsx类型组件

    AppComponent.tsx

    /**
     *TypeScript中无法使用使用RN的react和react-native,因此前面需要安装@types/react和
     *@types/react-native来实现TypeScript中对react及react-native的支持
     */
    import React,{Component} from 'react';
    import {View,Text} from 'react-native'; 
    
    //导入PersonImpl类
    import {PersonImpl} from './PersonImpl';
    
    export default class AppComponent extends Component{
      
      componentDidMount(){
        //实例化PersonImpl类
        let person = new PersonImpl(20,'Tom');
        //调用PersonImpl对象的getInfo方法
        console.log(person.getInfo());
      }
      
      render(){
        return(
        	<View>
          	<Text>该组件是通过typescript实现</Text>
          </View>
        );
      }
    }
    
  • RN程序入口使用AppComponent.tsx文件

    注意不要将./index.js入口点文件更改为typescript语言,否则将在打包生产版本时遇到问题。
    index.js

    import {AppRegistry} from 'react-native';
    import {name as appName} from './app.json';
    //导入tsx组件AppComponent
    import AppComponent from './AppComponent';
    
    AppRegistry.registerComponent(appName, () => AppComponent);
    
    
  • 编译.ts/.tsx文件

    在项目的跟目录下执行tsc命令对.ts/.tsx文件进行编译(通过编译检查TS文件合法性,如果出现错误会在该编译阶段抛出,避免了JS在运行时抛出)

    cd projectRoot
    tsc 
    

    编译后在指定的路径下生成对应的.js文件

  • 运行项目

    react-native run-android
    

    打印结果及展示页面

    print info name = Tom,age = 20
    

    在这里插入图片描述

至此,我们可以在RN中愉快的使用TypeScript来替代JavaScript

扩展

RN测试工具

Jest

Jest 是基于 Jasmine 的JavaScript 测试框架,是 React.js 默认的单元测试框架。相比其它框架,具有以下特点:

  • 适应性:Jest 是模块化、可扩展和可配置的;
  • 沙箱和快速:Jest 虚拟化了 JavaScript 的环境,能模拟浏览器,并且并行执行;
  • 快照测试:Jest 能够对 React 树进行快照或别的序列化数值快速编写测试,提供快速更新的用户体验;
  • 支持异步代码测试:支持 promises 和 async/await;
  • 自动生成静态分析结果:不仅显示测试用例执行结果,也显示语句、分支、函数等覆盖率

详细配置及使用参考:

react-test-renderer

react-test-renderer该工具提供了一个React的渲染器,可以用来将 React 组件渲染成纯 JavaScript 对象,不需要依赖于 DOM 和原生移动环境。

本质上,该包可以在无需使用浏览器或 jsdom 的情况下,轻松地抓取由 React DOM 或 React Native渲染出的平台视图层次结构(类似于DOM树)

  • 示例

    //导入react-test-renderer工具包
    import TestRenderer from 'react-test-renderer';
    
    //通过函数返回一个组件
    function Link(props) {
      return <a href={props.page}>{props.children}</a>;
    }
    
    //通过TestRenderer的create创建实例对象(参数是组件)
    const testRenderer = TestRenderer.create(
      <Link page="https://www.facebook.com/">Facebook</Link>
    );
    console.log(testRenderer.toJSON());
    
    
    /*
     *打印出视图层次结构
       { 
          type: 'a',
          props: { href: 'https://www.facebook.com/' },
          children: [ 'Facebook' ] 
       }
    */
    

更多使用参考:测试渲染(Test Renderer)

Logo

智屏生态联盟致力于大屏生态发展,利用大屏快应用技术降低开发者开发、发布大屏应用门槛

更多推荐