React Native使用TypeScript
新建项目
react-native init TSReactNative
TypeScript配置
npm install -g typescript
npm install -g typings
也可以在项目下安装typescript: 根目录下运行
npm install typescript
安装types
npm install @types/react @types/react-native
增加tsconfig.json文件,可以用如下命令生成:
tsc --init --pretty --sourceMap --target es2015 --outDir ./lib --rootDir ./ --module commonjs --jsx react
使用typescript编写组件,根目录新建demo.tsx文件
import * as React from 'react';
import {View} from 'react-native';
interface props {
title?: any;
}
export default class Demo extends React.Component<props> {
render() {
return (
<View style = {{height: 100, width: 100, backgroundColor: 'red'}}>
</View>
)
}
}
编译
在项目根目录下使用tsc命令编译文件
注意:如果出现 node_modules/@types/react-native/globals.d.ts:36:15 - error TS2300: Duplicate identifier 'FormData'. 的错误
修改tsconfig.json文件,在compilerOptions增加以下代码,即可编译成功
"lib": [
"es2015.promise",
"es2015",
"es2016"
],
使用
在App.js里面导入
import Demo from './lib/demo';