如何在React-Native上使用Typescript

首先安裝腳手架:node

$ yarn global add create-react-native-app

建立項目:react

create-react-native-app xxx

進入項目並啓動:android

cd xxx
yarn start

若是不用ts,如今就能夠正常使用了ios

 

畢竟要用ts,還得折騰一番:es6

安裝依賴typescript

yarn add typescript tslint -D 
yarn add @types/react @types/react-native @types/react-dom -D

咱們還須要rimraf,併發地清理從ts編譯過來的js文件的輸出文件夾,併發地運行npm腳本:npm

yarn add concurrently rimraf -D

 

設置Typescript config (tsconfig.json)使用tsc命令,或者在項目文件夾中手動建立。json

tsc --init

 

須要在tsconfig.json文件手動添加react-native

{
    "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
}

須要注意一些細節:babel

咱們但願將Typescript應用程序的全部代碼存儲在src文件夾下的文件夾/子文件夾中。用「rootDir」:「src「,確保你的根目錄爲src或者也能夠手動更改

並把babel.config.js文件扔到這個文件夾內

 

而後安裝依賴:

yarn add react-native-scripts

將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 "

將main更改成:

"main":"./node_modules/react-nativescripts/build/bin/crna-entry.js"

 這意味着咱們的應用程序從這個crna-entry.js 開始打開這個文件,你會發現它引用了咱們的App.js 

var _App = require('../../../../App');

這意味着它但願app模塊位於項目根目錄下的app .js 文件中。

ts編譯器將會在build文件夾下輸出編譯事後的.js文件

所以,爲了讓CRNA可以處理咱們已經更改的文件夾結構和Typescript配置,讓咱們在項目文件夾下添加一個App.js ,它將在src/App中導出咱們的App組件。Typescript編譯器將輸出到build文件夾。

在項目根目錄添加一個app.js文件:

import App from './build/App';
export default App;

 

注意建立typescript文件後綴爲.tsx

運行命令便可

yarn buildAndStart
相關文章
相關標籤/搜索