react-native如今是愈來愈火了,公司也在開始使用react-native構建項目了,就此將本身的踩坑經歷記錄於此javascript
這裏有詳細的步驟,在此就不贅述了。按照步驟來應該不會有什麼問題html
這裏主要介紹一下在react native中使用typescript的方法以及我在此過程當中踩過的坑。java
typescript
以及typings
npm install -g typescript typings
tsconfig.json
tsc --init
tsconfig.json裏面的配置項能夠根據本身的具體項目來進行,有相關的文檔能夠進行查閱react
typings
安裝依賴typings install dt~react --global --save
可是會一直報下面這個錯誤typescript
message:Attempted to compile "react" as a global module, but it looks like an external module. You'll need to remove the global option to continue
在網上搜了半天也沒有搜到,難道react-native默認安裝的react依賴是模塊化的而非全局化的嗎? 就是由於這個致使react在setup.tsx中會報錯:npm
import React,{ Component } from "react"; import { Component } from "react"; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; class Root extends React.Component<any, any>{ render() { return ( <Text>this is a test,wyf</Text> ) } } export default () => Root
提示React module is not existed
,一臉懵逼,而後搜索這個錯誤信息,找到以下的解決方案,將上面第一行改成:json
import * as React from "react";
這樣確實能夠解決問題,可是以後問題又來了,因爲react-native不是全局的,Text沒有類型說明,因此又通不過,最終仍是須要用typings
全局安裝react-native
最後嘗試了終極辦法:gulp
typings
typings --init
就會在項目根目錄生成typings.json
,而後經過直接配置該文件react-native
{ "globalDependencies": { "react": "registry:dt/react#0.14.0+20161024223416", "react-native": "registry:dt/react-native#0.29.0+20160709063508", } }
typings install
結果竟然成功了。真是歷盡千辛萬苦啊模塊化
(2)使用gulp實時編譯typescript
npm install --global gulp
npm install --save-dev gulp
var gulp = require('gulp'); var ts = require('gulp-typescript'); var tsProj = ts.createProject('tsconfig.json'); gulp.task('tsc', function () { var tsResult = gulp.src('js/**/*.ts') .pipe(ts(tsProj)) .pipe(gulp.dest('built/')); }); gulp.task('tsc:w', ['tsc'], function () { gulp.watch('js/**/*.ts', ['tsc']); });
其中src文件和built文件是指須要編譯的文件目錄和目標文件目錄,具體能夠參考這裏
而後執行gulp tsc:w
就能夠實現實時編譯了 菜鳥踩坑中,將本身的經驗記錄下來