在ReactNative中使用Typescript
少俠放心,跟着我的這個步驟走,保你完美在RN項目中使用Typescript,廢話不多說,走你
1.全局安裝create-react-native-app
yarn global add create-react-native-app
2.創建項目
create-react-native-app projectname(你的項目名字)
3.cd到你的項目文件夾中
4.安裝typescript依賴
yarn add typescript tslint -D
yarn add @types/react @types/react-native @types/react-dom -D
5.安裝其他依賴
yarn add concurrently rimraf -D
yarn add ts-jest @types/jest @types/react-test-renderer -D
6.在你的項目根目錄下創建一個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-scripts
8.將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>不成功加我qq:291678978,手把手教學好吧</Text>
</View>
)
}
}
12.執行命令:yarn buildAndStart,然后靜靜的等待運行成功,用你偉大的expo掃描成功的二維碼就可以看到偉大的勝利;注:如果想在瀏覽器看到你的二維碼,可再單獨執行一下yarn start
然后就可以很開心的在項目里寫TypeScript代碼了,例如項目中tsx目錄下有test.tsx文件,我們在import這個文件時,就像import一個js文件就可以了(注:ts文件后綴名ts和tsx都可以,不過在當前環境下后綴名寫成ts好像有問題,如果有問題的話將后綴名改成tsx即可,親測有效)
import './tsx/test'