關於
React Native
的詳細介紹我就不敘述了,他是使用js構建原生app的開發框架。一次變編碼多平台運行,非常強大。但是個人不喜歡js的過於靈活(弱類型)
的語法。強大的強類型語言Typescript(簡稱TS)
是我的首選,他可以編譯成JavaScript
,編譯成的JavaScript代碼可讀性很好,但是這不是關鍵,關鍵是TS
開發和調試效率極高。
但是React Native
官方是使用js
的開發的,如果如果使用TS開發React Native的關鍵是transformer
。
eact-native結合的關鍵是使用轉換器
初始化項目
react-native init YahuiApp
cd YahuiApp
yarn add --dev react-native-typescript-transformer typescript @types/react @types/react-native
用vscode打開 添加配置文件
配置Typescript
新建文件 tsconfig.json
內容為
{
"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
內容為
{
"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文件 內容為:
module.exports = {
getTransformModulePath() {
return require.resolve('react-native-typescript-transformer');
},
getSourceExts() {
return [ 'ts', 'tsx' ]
}
};
編寫代碼
在 src文件夾里新建main.tsc
文件
代碼為:
import React, { Component } from "react";
import {
StyleSheet,
Text,
View
} from "react-native";
interface Props {
}
interface State {
}
export default class App extends Component<Props, State> {
render() {
return (
<View style={styles.container}>
<Text style={styles.text}>
Welcome to React Native!
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#F5FCFF",
} as React.ViewStyle,
text: {
fontSize: 20,
textAlign: "center",
margin: 10,
} as React.TextStyle,
});
AppRegistry
import {
AppRegistry,
} from 'react-native';
import App from "./src/main";
AppRegistry.registerComponent('YahuiApp', () => App);
至此 您的使用TS開發React Native的項目環境搭建好了
轉載請注明出處:http://blog.yahui.wang/2017/08/26/react-native-typescript-init-debug/