關(guān)于React Native的詳細(xì)介紹我就不敘述了蚜锨,他是使用js構(gòu)建原生app的開(kāi)發(fā)框架。一次變編碼多平臺(tái)運(yùn)行,非常強(qiáng)大债查。但是個(gè)人不喜歡js的過(guò)于靈活(弱類(lèi)型)的語(yǔ)法。強(qiáng)大的強(qiáng)類(lèi)型語(yǔ)言Typescript(簡(jiǎn)稱(chēng)TS)是我的首選瓜挽,他可以編譯成JavaScript盹廷,編譯成的JavaScript代碼可讀性很好,但是這不是關(guān)鍵久橙,關(guān)鍵是TS開(kāi)發(fā)和調(diào)試效率極高俄占。
但是React Native官方是使用js的開(kāi)發(fā)的,如果如果使用TS開(kāi)發(fā)React Native的關(guān)鍵是transformer管怠。
eact-native結(jié)合的關(guān)鍵是使用轉(zhuǎn)換器
初始化項(xiàng)目
react-native init YahuiApp
cd YahuiApp
yarn add --dev react-native-typescript-transformer typescript @types/react @types/react-native
用vscode打開(kāi) 添加配置文件
配置Typescript
新建文件?tsconfig.json內(nèi)容為
{"compilerOptions": {"module":"es2015","target":"es2015","moduleResolution":"node","jsx":"react-native","noImplicitAny":true,"experimentalDecorators":true,"preserveConstEnums":true,"sourceMap":true,"watch":true,"allowSyntheticDefaultImports":true},"filesGlob": ["src/**/*.ts","src/**/*.tsx"],"exclude": ["index.android.js","index.ios.js","build","node_modules"]}
新建文件?tslint.json?內(nèi)容為
{"rules": {"class-name":false,"comment-format": [true,"check-space"],"indent": [true,"spaces"],"no-duplicate-variable":true,"no-eval":true,"no-internal-module":true,"no-trailing-whitespace":true,"no-unsafe-finally":true,"no-var-keyword":true,"one-line": [true,"check-open-brace","check-whitespace"],"quotemark": [true,"double"],"semicolon": [true,"always"],"triple-equals": [true,"allow-null-check"],"typedef-whitespace": [true,? ? ? ? ? ? {"call-signature":"nospace","index-signature":"nospace","parameter":"nospace","property-declaration":"nospace","variable-declaration":"nospace"}? ? ? ? ],"variable-name": [true,"ban-keywords"],"whitespace": [true,"check-branch","check-decl","check-operator","check-separator","check-type"]? ? }}
配置React Native Packager
根目錄新建rn-cli.config.js文件 內(nèi)容為:
module.exports = {
getTransformModulePath() {
return require.resolve('react-native-typescript-transformer');
},
getSourceExts() {
return [ 'ts', 'tsx' ]
}
};
編寫(xiě)代碼
在 src文件夾里新建main.tsc文件
代碼為:
importReact, { Component }from"react";import{? ? StyleSheet,? ? Text,? ? View}from"react-native";interface Props {}interface State {}exportdefaultclassAppextendsComponent{? ? render() {return(Welcome to React Native!);? ? }}conststyles = StyleSheet.create({container: {flex:1,justifyContent:"center",alignItems:"center",backgroundColor:"#F5FCFF",? ? }asReact.ViewStyle,text: {fontSize:20,textAlign:"center",margin:10,? ? }asReact.TextStyle,});
AppRegistry
import{? ? AppRegistry,}from'react-native';importAppfrom"./src/main";AppRegistry.registerComponent('YahuiApp',()=>App);
至此 您的使用TS開(kāi)發(fā)React Native的項(xiàng)目環(huán)境搭建好了