少俠放心,跟著我的這個(gè)步驟走,保你完美在RN項(xiàng)目中使用Typescript尿背,廢話不多說(shuō)奠蹬,走你
1.全局安裝create-react-native-app
yarn globaladd create-react-native-app
2.創(chuàng)建項(xiàng)目
create-react-native-app projectname(你的項(xiàng)目名字)
3.cd到你的項(xiàng)目文件夾中
4.安裝typescript依賴
yarnadd typescript tslint -Dyarnadd @types/react @types/react-native @types/react-dom -D
5.安裝其他依賴
yarnadd concurrently rimraf -Dyarnadd ts-jest @types/jest @types/react-test-renderer -D
6.在你的項(xiàng)目根目錄下創(chuàng)建一個(gè)tsconfig.json文件,將以下代碼復(fù)制進(jìn)去即可
{"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
yarnadd 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中代碼清空,并將以下代碼替換
importAppfrom'./build/App';exportdefaultApp;
11.創(chuàng)建一個(gè)src文件夾,將babel.config.js文件放在src文件夾下垛玻,同時(shí)在src文件夾下創(chuàng)建一個(gè)App.tsx文件,App.tsx文件中代碼如下
importReact, {Component} from"react"import{View,Text} from"react-native"exportdefaultclassAppextendsComponent{? render() {return(? ? ? ? ? ? ? 不成功加我qq:291678978奶躯,手把手教學(xué)好吧? ? ? ? ? )? }}
12.執(zhí)行命令:yarn buildAndStart帚桩,然后靜靜的等待運(yùn)行成功,用你偉大的expo掃描成功的二維碼就可以看到偉大的勝利嘹黔;注:如果想在瀏覽器看到你的二維碼账嚎,可再單獨(dú)執(zhí)行一下yarn start
然后就可以很開(kāi)心的在項(xiàng)目里寫(xiě)TypeScript代碼了,例如項(xiàng)目中tsx目錄下有test.tsx文件儡蔓,我們?cè)趇mport這個(gè)文件時(shí)郭蕉,就像import一個(gè)js文件就可以了(注:ts文件后綴名ts和tsx都可以,不過(guò)在當(dāng)前環(huán)境下后綴名寫(xiě)成ts好像有問(wèn)題喂江,如果有問(wèn)題的話將后綴名改成tsx即可召锈,親測(cè)有效)
import'./tsx/test'