Introduction to TypeScript
TypeScript is open sourced by Microsoft on Github.
TypeScript is a superset of JavaScript with additional support for strong typing and ES6.
TypeScript code is eventually compiled into JavaScript code for execution, which in turn runs on any browser.
TypeScript environment configuration
For the development environment configuration of TypeScript in the ReactNative project, refer to the official TypeScript configuration
· 创建 ReactNative 工程
react-native init MyRnDemo
· cd MyRnDemo
· 创建 src(之后的ts代码存放目录)目录
mkdir src
· 将默认创建的 App.js 文件移动到 src 目录下
mv App.js src
· 将 __tests__ 目录移动到 src 目录下(主要用于单元测试)
mv ./__tests__/ ./src/__tests__/
· 测试是否可运行
react-native run-android
· 修改 index.js 中的 App.js 的导入信息为
import App from './lib/App';
· 添加 typescript 运行环境
npm install --save-dev typescript
· 使用 tsc 脚本创建 typescript 编译环境
./node_modules/.bin/tsc --init --pretty --sourceMap --target es2015 --outDir ./lib --module commonjs --jsx react
· 添加 types 的编译环境以及 src 目录到 tsconfig.json中
{
"compilerOptions": {
// other options here
"types": ["react", "react-native"],
},
"include": ["./src/"]
}
· 添加 react 库的 typescript 编译环境
npm install --save-dev @types/react @types/react-native
· 将 src 目录中 App.js 重命名为 App.tsx,并修改 react 库的导入信息为:
import * as React from "react";
import {Component} from "react";
· 执行 ts->js 的代码转换监听器,并保持开启
./node_modules/.bin/tsc -w
· 新开一个 Terminal 窗口运行项目
react-native run-android