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
就能够实现实时编译了 菜鸟踩坑中,将本身的经验记录下来