一. RN-TS环境搭建
1. 安装RN脚手架
yarn add create-react-native-app -g
yarn global add typescript
2. 创建项目文件夹
create-react-native-app RN-TS
3. 进入文件夹
cd RN-TS
4. 安装包
yarn add typescript tslint @types/react @types/react-native @types/react-dom -D
5. 在项目目录下运行 tsc --init命令生成tsconfig.json文件
将原内容删掉,替换为以下内容
{
"compilerOptions": {
"module":"es2015",
"target": "es2015",
"jsx": "react",
"rootDir": "src",
"outDir": "build",
"allowSyntheticDefaultImports": true,
"noImplicitAny": true,
"sourceMap": true,
"experimentalDecorators": true,
"preserveConstEnums": true,
"allowJs": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"skipLibCheck": true,
"moduleResolution":"Node"
},
"filesGlob": [
"typings/index.d.ts",
"src/**/*.ts",
"src/**/*.tsx",
"node_modules/typescript/lib/lib.es6.d.ts"
],
"types": [
"react",
"react-dom",
"react-native"
],
"exclude":[
"build",
"node_modules",
"jest.config.js",
"App.js"
],
"compileOnSave": false
}
6. 安装yarn add concurrently rimraf react-native-script -D,之后将以下代码替换掉package.json下的scripts的语句
"start": "react-native-scripts start",
"eject": "react-native-scripts eject",
"android": "react-native-scripts android",
"ios": "react-native-scripts ios",
"test": "node node_modules/jest/bin/jest.js",
"lint": "tslint src/**/*.ts",
"tsc": "tsc",
"clean": "rimraf build",
"build": "yarn run clean && yarn run tsc --",
"watch": "yarn run build -- -w",
"watchAndRunAndroid": "concurrently \"yarn run watch\" \"yarn run android\"",
"buildRunAndroid": "yarn run build && yarn run watchAndRunAndroid ",
"watchAndRunIOS": "concurrently \"yarn run watch\" \"yarn run ios\"",
"buildRunIOS": "yarn run build && yarn run watchAndRunIOS ",
"watchAndStart": "concurrently \"yarn run watch\" \"yarn run start\"",
"buildAndStart": "yarn run build && yarn run watchAndStart "
7. 将package.json中的main设置为:
./node_modules/react-native-scripts/build/bin/crna-entry.js
8. 将App.js里的内容替换为
import App from './build/App'
export default App
9. 在项目下新建src目录,并把babel.config.js放在src文件夹下
10. 在src下新建一个App.tsx文件拷入以下代码,然后运行yarn buildAndStart
import React, { Component } from "react"
import { View, Text } from "react-native"
export default class App extends Component {
render() {
return(
<View>
<Text>hello</Text>
</View>
)
}
}
11. 打开你手机端的expo软件扫描出现的二维码,如果手机上出现hello,说明环境搭建成功了