怎么在ReactNative里面使用Typescript
今天來搞一搞怎么搭建一個可以使用Typescript的ReactNative環境好吧,一句廢話不多說,直接開始好吧
1.全局安裝create-react-native-app
yarn global add create-react-native-app?
?
2.create-react-native-app 你的項目名稱 ? ?
?
例如:create-react-native-app myApp運行完選擇blank回車等待就好
?
3.cd到你的項目文件夾中,準備安裝typeScript依賴
?
4.安裝typeScript依賴
yarn add typescript tslint -D yarn add @types/react @types/react-native @types/react-dom -D?
5.繼續安裝其他依賴
yarn add concurrently rimraf -D?
6.通過tsc --init生成tsconfig.json,或者手動創建一個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 }
?
?7.安裝react-native-scripts
yarn add react-native-scripts8.將package.json中的"scripts"配置清空,并將以下代碼替換
"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 "}
9.將package.json中的"main"配置清空替換為以下代碼
"main": "./node_modules/react-native-scripts/build/bin/crna-entry.js"10.將App.js中代碼清空,并將以下代碼替換
import App from './build/App'; export default App;11.創建一個src文件夾,將babel.config.js文件放在src文件夾下,同時在src文件夾下創建一個App.tsx文件,App.tsx文件中代碼如下
import React, { Component } from "react" import { View, Text } from "react-native"export default class App extends Component {render() {return(<View><Text>紅牛維生素功能飲料</Text></View> )} }?
12.執行yarn buildAndStart即可
注意在此環境下編寫ts文件時,后綴名寫為tsx,暫時不知道什么原因,寫ts后綴名有問題
還有特別注意一下,在此環境導入圖片時,用import有問題,只能用require,這個問題暫時不知道原因
?
更多專業前端知識,請上 【猿2048】www.mk2048.com
總結
以上是生活随笔為你收集整理的怎么在ReactNative里面使用Typescript的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JS实现2048
- 下一篇: 浏览器兼容问题及解决方案